When Joseph finds out that Mary is pregnant, it must have been a terrible surprise. They were betrothed, but had not yet lived as husband and wife, so he knew the child was not his. (The Jewish wedding ceremony had two parts: betrothal, which was a binding exchange of consent in front of witnesses, followed a few months later by the bride moving into her husband’s home.) Joseph obviously reached the only conclusion he could reach, which was that Mary had been unfaithful to him with another man. And because a betrothal was binding, it could only be dissolved by death or divorce.
Joseph’s resolve to “divorce her quietly” (Matthew 1: 19) is an important detail. The penalty for adultery was death by stoning, so Joseph’s decision indicates that he was unwilling to expose Mary to the full force of the law (in fact, in the above verse Matthew explains that Joseph was “a righteous man, yet unwilling to expose her to shame.”) Joseph changes his mind about the divorce when he receives the message from the angel of the Lord, who tells him that her child was conceived through the Holy Spirit (and not through sexual relations with another man). This is a game-changer for Joseph, who then does as the angel commands and takes Mary into his home.