There are some situations when people tend to behave less politely than they normally would and being in pain is one of them. It has even been shown that for the many people who don’t often use such language, swearing increases pain tolerance, among its other functions.
Either way, it may be hurtful when directed at others and this Redditor raised a question about whether it would be a good idea to apologize for swearing at her doctor while giving birth.
More info: Reddit