When you go through sex education at 11 or 12 years old, one of the first things you learn about is erections. I have a very vivid memory of the day my Year 7 class was told that just talking about erections could lead to actual erections, which cued bashful
Lee Suckling: Puberty hangover that still catches men out
A spontaneous erection refers to one that happens out of nowhere. Morning erections aren't actually all that random: they are technically the result of nocturnal penile tumescence, or fluctuations in testosterone levels while you're sleeping. A typical healthy male will actually experience three to five erections while asleep, each lasting 25 to 35 minutes.
Some random erections are known as emotional erections. These occur when the subconscious links a thought, taste, touch, smell, or visual to a prior memory with sexual context. Emotional erections can happen when you hear a foreign accent, for example, or when you smell a particular perfume. Objects cause spontaneous erections too: a man's subconscious could link something like a pair of high heels or a bridal gown together with erotic connections in the psyche. In all situations, embarrassment ensues because people think a random erection is humiliating.
When there's no perceived sexual stimuli – even a subconscious one – spontaneous erections can still happen to some guys when emotions are high. They can happen when you're afraid (e.g. watching a scary movie or hearing a noise outside), upset (like when you're arguing with your partner), or ecstatic (for instance when you win a sporting competition). They're actually not uncommon during exercise like weight-lifting - and not because there are sweaty bodies around you in a gym, but because of changes in the autonomic nervous system to your blood flow and breathing.
Spontaneous erection don't usually mean a man wants to have sex (or masturbate) then and there. It's an ill-timed physical response, not a sign of perversion. This won't help most men's shame on the occasions they experience a random erection, nor helps alleviate horror, disgust, or hilarity for anybody who notices that tent in your shorts.
It's not weird or unhealthy to have random erections, and all you can do it wait them out. It's important to remember that while a hard penis feels obvious to the person with it, there's little reason for anxiety about others noticing it. It can be disguised by obscuring it with clothing (or that famous notebook!), tucking it under your belt, or even just sitting down. Distract yourself, think about something else, reposition, and stop looking down. Unwanted erections happen to men throughout the day, and they go away as fast as they pop up.