According to the teachings of the Bible, the Prophets did commit sins, grave sins.
Prophet David committed adultery, (2 Samuel 11:4),
Prophet Solomon committed idolatry, (1 Kings 11:10).
However, according to the teachings of Islam, Prophets and Messengers of God Almighty are specially protected and cannot commit sins.
The criterion is that, as teachers, they must practise themselves first what they are trying to teach others.
They can however, make an error of judgement, but even that error is for righteous intentions. As they are human beings however and do not have knowledge of the future (except what Allah has given them) they can make errors.
As we read in the case of Prophet Yunus (Jonah) (pbuh) that when God Almighty had informed him that punishment will now come as after many, many years of preaching, his people stubbornly refused to believe.
Upon receiving this revelation he left his community. He was hasty. He failed to wait until the order from God Almighty came for him to emigrate. Later, when he repented he was forgiven by God Almighty.
However, due to his error, his community was saved. For when they saw the punishment coming the king and the people realised that that was what Jonah forewarned them about, they all fell into prostration before God, repented, were forgiven, and punishment averted. Prophet Yunus (Jonah) (pbuh), later returned to his community, as commanded by God Almighty and continued preaching to them, (The Quran 10:48).
In the case of Prophet Muhammad (pbuh), once he was talking to a group of Quraishite leaders who had come to see him to know about his deen. As he was engrossed in conversation with them, his wife’s cousin an old blind man, Ibn Ummul-Maktum who was already a Muslim, came to see him and began to ask him questions. The blind man interrupted again and again, while the Prophet (pbuh) was engrossed in conversation with leaders of the Quraish.
At this, the Prophet (pbuh) spoke to him a little harshly, because he thought that the blind man can come to him anytime and learn, whereas these leaders, who had come to learn from him, presented an exceptional opportunity to preach to them. And even if only one of them accepted Islam, it would strengthen the small Muslim community.
His intention was obviously pure and based on serving his mission, the promulgation of his deen.
However, Allah (SWT) was displeased and the Prophet was corrected, because he was sent also as one at highest pinnacle of character, (The Quran 80:1-13, 68:4).
In response to the answer above, sometimes another question follows:
But Prophet Adam committed a sin, although he was a Prophet of God, please explain?
The fact is that Adam (pbuh) was not a Prophet when he made the mistake of eating from the forbidden tree.
The station of Prophethood was bestowed upon him later, when he was commanded to teach his children the religion of Islam.