Exception throwing in C#

This is one of the tricky concepts that ending up as an interview question in an investment bank. I was asked to differentiated between C# “throw” and “throw ex” and also explain their MSIL counter parts.  I managed to get the first bit right but got the later wrong. So just to clarify for myself and others, this is how they are treated:

C# Keyword Behaviour MSIL Counterpart
throw ex This will throw the exception you’ve just caught in your catch block but stack trace will be overridden(cleared). The place where you do “throw ex” will be now treated as the point of origin. This gets translated into MSIL as “throw”
throw This will simply re-throw the exception just caught as if the exception was never caught. It retains the full stack trace. This gets translated into MSIL as “rethrow”. This keyword doesn’t exist in C# and may not be so intuitive to guess.

As far as where you can use them, it depends on your application and the layer in which they occur i.e. business, data or presentation layer.  Sometimes you may need to override sensitive information so you can do “throw ex” or sometimes you may just want to log the info for auditing and re-throw it will full stack trace.

Have a nice day!

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s