Mary was pregnant before she and Joseph came to live together. Joseph knew the child was not his. In Jewish law if a woman was found not to be a virgin before marriage she could be stoned to death:
But if this charge is true, and evidence of the young woman’s virginity is not found, they shall bring the young woman to the entrance of her father’s house and there the men of her town shall stone her to death…
Joseph is a just man and knows the law but he is also a compassionate and merciful man. Under Jewish law the husband would have to bring the charge against her but Joseph did not want to subject Mary to a trial (Numbers 5:11-31) and possible punishment. He therefore sought to divorce Mary quietly (Matthew 1:19) so that no harm would come to her. In Joseph we see an extraordinary man who, if he believed Mary had cheated on him, would have been hurt and angry but still sought to be merciful and compassionate. The angel appears to Joseph to allay his fears that Mary has violated the law and assure him that everything that is happening is by God’s power and is part of God’s plans. Joseph, like Mary in the Gospel of Luke, then submits to the will of God.