Joseph discovered his young wife to be is with child (Matthew 1:18-19). Betrothal in the Second Temple Period was a legally binding relationship which could be set aside only through a divorce-like proceeding. A betrothal period could take up to twelve months (m.Ket 5:2), during which time the woman is still under the authority of her father.
Normally there were no sexual relations between the engaged couple, although it is likely that sort of thing did happen. If the man lived with his father-in-law during the betrothal, he cannot divorce his wife is she is found not to be a virgin. There is a whole section of the Mishnah (Ketuvim) dealing with engagements and breaking those engagements. It is impossible to be certain that the practices described there were in force at the time Jesus was born, but it is likely that some of the things we read there reflect the issues with which Joseph dealt.
Since Mary is pregnant, she must have been unfaithful. Joseph therefore decides to divorce her “quietly” because he does not want to shame her. The verb δειγματίζω is used for the shaming of a woman caught in adultery, as the the scribes wanted to do to a woman caught in adultery in John 8:2. Dio Chryssostom mentions a Cyprian law requiring an adulteress to cut her hair and be “subject to contempt by the community” (Dio Chrys. 47; BDAG). This form of the verb does not appear in the LXX, but the compound verb παραδειγματίζω appears 6x. In Num 25:4 it describes the public hanging of those who fornicated with the prostitutes from Baal-Peor (compare PsSol 2:12-14, a possible allusion to that story).
The divorce (ἀπολύω) is to be “quiet,” an adverb (λάθρᾳ) often meaning “in secret” or “in private.” In Matt 2:7, for example, Herod summons the wise men “in secret.” It is occasionally used outside of the New Testament with the sense of “not going through proper channels.” It is possible that Joseph, being a poor man, did not feel it necessary to spend the money and time to properly punish her, so he would dissolve the marriage without bringing it before proper authorities who would (perhaps) insist on a shaming of Mary and (undoubtedly) money from Joseph.
Since Joseph was described as a “righteous man,” it is possible that he thought he was obligated by the Law divorce Mary (Nolland, Matthew, 95). Numbers 5:11-31 may indicate that if a man discovers his wife in adultery a divorce is required, as well as a public shaming. It is also possible that Joseph did not want to shame himself by declaring to the public that his betrothed wife had been unfaithful. While the text says that it is Mary’s shame that is in mind, Joseph would have a certain level of humiliation when the news became public
Whatever his motives, Joseph is describe as “doing the right thing” and preserving Mary from a public disgrace for adultery.