C# Re-throwing Your Exceptions (the right way)

There are a lot of programmers out there who are unaware of what really happens when they re-throw Exceptions within their applications and that there are 2 ways in which it can be done. Based on what you are trying to accomplish there is a right way and a wrong way.

Lets say you are using an error/exception logging system and you want to make sure and preserve everything that happened when the Exception was thrown as well as the code which caused it. To get to the logging system you may be bubbling up the Exceptions through your code to a main Exception Handler.

Here is the most common re-throwing of exceptions which I have seen in my own earlier code as well as those developers whose code I have worked on.

 try { //your code does something bad }
catch (Exception ex) { throw ex; }

Discussion: the above code actually creates a brand new Exception within the current scope, this effectively deletes the Stack Trace held within the bubbling Exception. You have now lost all the information telling you what happened when the Exception was thrown and what code caused it. This is very bad when bubbling your Exceptions for logging.

try { //Your code does something bad }
catch (Exception ex) { throw; }

Discussion: The above code now just passes along any exception which is caught in the try-catch preserving the entire Stack Trace for your debugging enjoyment. This is very good when bubbling your Exceptions for logging.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s