Properly throwing exceptions in C#

While taking a proficiency test for a job, the following question arose (which I got wrong):

Explain the difference between

catch (Exception ex) {
	//exception handling code
	throw ex;
}

and

catch (Exception ex) {
	//exception handling code
	throw;
}

At the time, I thought they were the same so I was at a loss for an answer. The short answer is the latter preserves the full stacktrace and the former truncates it. Quite handy to know.

If repackaging the exception is necessary, then it should be passed to the new exception type like below (at least this I was already doing correctly!):

catch (Exception ex) {
	//exception handling code
	throw new MyException("A lucid exception message.", ex);     
	//MyException is of course some real exception
}

A good explanation can be found at Scott Dorman’s blog.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>