The human body is designed to protect itself from invaders like bacteria and viruses. Sometimes its defensive actions can turn out to be quite unpleasant, however. Vomiting is a prime example. Not only is it traumatic and uncomfortable, it's also downright gross. But throwing up does serve a purpose, particularly when you get a nasty stomach bug.
To understand a little more about how vomiting works and why it's sometimes necessary, you have to first look at how the stomach and brain communicate with one another. The digestive tract is lined with endocrine sensor cells, officially known as enterochromaffin cells, or "EC cells." Amazingly, these cells contain around 90 percent of the body's serotonin [source: Donnerer]. It is believed that when the EC cells detect something bad in the digestive system, such as the rotavirus, they use chemical messengers like serotonin to spread the word to the enteric nervous system (ENS). The ENS, which is wired to the brain, is the part of the nervous system in charge of gastrointestinal responses. So once it gets word of a viral or bacterial infection, the ENS stimulates vomiting.
To better visualize this, imagine an intruder breaking into your home. If that happens, your alarm sends a message to an alarm company. The alarm company then calls the police. Such a system is designed with one purpose — to get the intruder out of your house. The same can be said of the alerts created by your body when you're sick with a stomach bug. The EC cells detect a microbial invasion. They then send out an alarm (serotonin messengers) to the alarm company (the ENS). The police (vomiting) then escort the intruder (the virus) out.
Thankfully, this process rarely happens instantly. Typically, the ENS also activates nausea, that sick feeling that lets you know vomiting is on the way. As for the action of throwing up, that's controlled by the stomach muscles. During vomiting, they work to push stomach contents up through the digestive tract rather than allowing them to continue through the intestinal phase of digestion. The gastrointestinal system has a different method for expelling bacteria and viruses that have already made it to the large intestine — diarrhea. Often, a stomach bug will necessitate this response as well as vomiting.