This is an expression that people use when they're shocked or surprised. This can be for positive reasons, like when your married sister says that she's pregnant:
...or for negative reasons like when someone has gotten in an accident.
When someone tells you good news, you might expect to say "congratulations". This would be the polite way to react if a coworker or not-very-close friend said that they were going to get married. But with someone really close like a close friend, "Congratulations" is too distant. So a more excited response like "Oh my God!" is better.