Joseph and Mary are engaged to be married, but before the marriage takes place Mary is found to be pregnant. Of course Joseph must be devastated since, to his mind, it could only mean that Mary had been unfaithful to him.
I am told that in those days Mary's betrothal to Joseph would have been considered as binding as a marriage contract. This makes sense to me because this story says that Joseph would have had to divorce her to break off the relationship. So Mary was already bound to Joseph as his wife, and wives who commit adultery ought to be stoned to death according to the Mosaic Law (Leviticus 20:10). But interestingly Joseph is called "a righteous man" because he chooses to abide by the higher law of compassion and mercy. Instead of seeking Mary's punishment, he plans on a secret divorce to protect her from public disgrace--or perhaps an even worse fate.
This must have been an incredibly painful and trying time for Joseph, and I have to wonder if God was purposely keeping him in the dark for a time to see what he would do with Mary in this situation. If this was in fact a test of Joseph's character, I'd say he passed with flying colors.
Fortunately an angel intervenes, explaining to Joseph that Mary is with child by the Holy Spirit. Joseph's devastation must have turned into relief and then into astonishment at this news. This is the child who was promised to the fathers of old, of whom the prophets spoke, whom every Israelite woman throughout the ages hoped to have the privilege to bear. This promise is being fulfilled and now grows in Mary's womb before his eyes.
Joseph married Mary and kept her a virgin until she gave birth. Not because sex is somehow a dirty and defiling thing. Rather it was to leave no doubt about the miracle of Mary's conception. Joseph wanted to make clear that he did not father this boy. God himself was his Father.