Good question; there is actually a biological reason for this!
Many animals (mammals particularly) including humans have something called the "fight, flight or freeze" response, an autonomic reaction to fear.
Thousands of years ago, this response would have been useful to us because we lived in a way that put us under certain dangers in which the ideal response would have been to either fight or flee what was terrifying us: for example in the case of running away from a large, angry bear moving towards us.
When we perceive a danger, we get anxious/scared. The danger prompts our adrenal glands to release a hormone called adrenaline, which travels all around our body and can cause all kinds of different responses evolved because initially, they would have helped us to survive certain threats.
One of these responses was feeling the need to urinate/defecate, or even involuntarily doing so in the most extreme situations. At one time, this was a helpful response to us as:
a) It would make us lighter and able to run away faster, and
b) It would quickly deter certain predators and possibly slow them down.
Obviously, in today's world, the response is no longer so useful at all and can actually cause considerable problems and even make someone more anxious. However, the evolutionary response remains to a considerable extent and we have to seek out different ways to cope with it.