Rob Kraft's Software Development Blog

Software Development Insights

The Correct Way to Re-Throw An Exception – .Net Tip

Posted by robkraft on March 6, 2013

When catching and re-throwing an exception, you should include the original exception as a 2nd parameter.  Including the original exception may provide a deeper stack trace that will assist you with solving the exception.

This syntax may not include the full stack trace.

This syntax may not include the full stack trace.

In the code above, if an error occurs in methodWithoutCatch(), the call stack returned will show “methodWithTryCatch” as the deepest method in the stack.

System.Exception: Additional Error Info: blah blahObject reference not set to an instance of an object.
at WindowsFormsApplication6.Form1.methodWithTryCatch(String y) in ...\Form1.cs:line 34 at WindowsFormsApplication6.Form1.button1_Click
This example will include the full call stack.

This example will include the full call stack.

However, if you include the original exception in the throw as shown in the second throw example, then the call stack returned will show “methodWithoutCatch” as the deepest method in the stack.

System.Exception: Additional Error Info: blah blahObject reference not set to an instance of an object.
---> System.NullReferenceException: Object reference not set to an instance of an object.
at WindowsFormsApplication6.Form1.methodWithoutCatch(String z) in ...\Form1.cs:line 40
at WindowsFormsApplication6.Form1.methodWithTryCatch(String y) in ...\Form1.cs:line 29
--- End of inner exception stack trace ---
at WindowsFormsApplication6.Form1.methodWithTryCatch(String y) in ...\Form1.cs:line 35
at WindowsFormsApplication6.Form1.button1_Click

Including the original exception as the second parameter of your new exception provides you with a better call stack.  In this example, it allows you to determine that the error occurred in the methodWithoutCatch method.  In the first case, you are left wondering if the methodWithTryCatch really caused the error, or if one of the three methods it called (method1, methodWithoutCatch, or method3) caused the error.

Advertisements

One Response to “The Correct Way to Re-Throw An Exception – .Net Tip”

  1. This is one of the best blogs I have read.

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 )

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

 
%d bloggers like this: