Because Joseph her husband was a righteous man and did not want to expose her to public disgrace, he had in mind to divorce her quietly.
Joseph loved Mary. He planned to marry her until he learned she was pregnant. Fully aware that the child was not his, he could have announced her condition and joined with the crowd that would’ve turned on her. But he didn’t.
Because he loved her, and because he was an honorable man, Joseph did what he thought was right. He decided to end the relationship quietly and let her retain her dignity.
However, this was the child of God, and Joseph was given assurance from God that Mary had not been with another man. When he woke from a God-given dream and realized that this baby was the fulfillment of prophecy, he did what the angel in the dream told him to do. He was able to enjoy a long marriage to a faithful wife.