Freigeben über


[C#] Properly Re-throwing Exceptions in C# (or .NET to be General)

If you've spent almost your entire college with Java and recently become a newbie to .NET and C# like me, you will probably the same question I asked myself today sooner or later (better sooner...): How to properly re-throw an exception in C#, and is it different from Java?

In fact, despite that many similarities between Java and C# as managed languages, how to re-throw exceptions makes a profound difference between them.

As you might remember, in Java, re-throwing a exception can be easily done by:

 try{
 ... // code that may throw exception
 } catch (Exception e) {
 throw e;
 }

The only line you need to look at is "throw e;", which is really not very interesting in the context of Java, but works entirely differently in C# if you write the same line:

 try
 { 
 ... // code that may throw exception 
 } 
 catch (Exception e) 
 { 
 throw e; 
 }

The difference is: In Java, when you do "throw e;", you are essentially re-throwing that exception "as-is", which means the original stack trace - the most important thing here - is preserved. While in C# (or VB and other .NET languages I assume), the same syntax will cause the stack trace to be overridden by the line that re-throw the exception, which is very unlikely what you want.

So, to answer the question of "How to properly re-throw exceptions in C#", you have two options:

1. Instead of "throw e;" just use "throw;", which works like a charm.

2. Create a new exception with the information of old one, such as "new newExp ( "Exception happened when I do bla-bla-bla", e )". This is usually more suitable for the case when you want to add some additional information about the error.

Hope this will help some other new C#ers as well! :)

 

One more thing, if you've been wondering what to do with an exception (especially those unchecked ones), here's a blogpost on "Coding Horror" by Jeff Atwood which contains a handy guideline for exception handling: https://www.codinghorror.com/blog/2004/07/rethrowing-exceptions.html 

* But note that author made a mistake about the difference I talked above and he clarified later in the comment. Don't be tricked :P  

 

 

  

Comments

  • Anonymous
    September 16, 2012
    The comment has been removed