Usage of on/in

I didn’t do well on the exam.
I didn’t do well in the exam.

Are the above two sentences grammatically correct? If yes, how do these two sentences vary semantically ?