November 28, 2004

Rethrowig exceptions - subtle difference between Java and .NET you better be aware of

Here is what I learnt from Jackie Goldstein's talk on .NET Worst Practices at the .Net Deep Dive conference in Tel-Aviv last Thursday. There is a subtle, but hugely important difference between how .NET and Java rethrow a caught exception.

In Java, when you do "throw ex", ex is being re-thrown as if it wasn't caught at all - no informantion about rethrowing is ever recorded and original stack trace info is preserved. If you do want to start exception's stack trace from the rethrowing point - oh, that's completely different story, you need to refill exception's stack trace using fillInStackTrace() method.

In .Net however, when you do "throw ex", ex is being re-thrown, but original stack trace info gets lost. The point where exception is rethrown is now becoming exception's origin. Here is what I mean. If you do follow your Java habits and write

using System;
public class MyApp
{    
    public static void F() 
    {
        throw new NotImplementedException("Too lazy to implement!");
    }

    public static void Main() 
    {
        try 
        {
            F();
        } 
        catch (Exception e) 
        {
            Console.WriteLine("Exception {0} has occured!", e.GetType());
            throw e; //Line 18
        }        
    }
}
you'll get:
Exception System.NotImplementedException has occured!

Unhandled Exception: System.NotImplementedException: Too lazy to implement!
   at MyApp.Main() in d:\projects\test\class2.cs:line 18
See, you've lost original exceptions's stack trace and now you gonna have really hard time to figure out what was wrong actually, where the exception was thrown at the first place.

So in .NET you have to use "throw" keyword (Throw in VB.NET) with no argument to perform a pure re-throwing of an exception - change th eline 18 to just "throw;" and the result will be

Exception System.NotImplementedException has occured!

Unhandled Exception: System.NotImplementedException: Too lazy to implement!
   at MyApp.F() in d:\projects\test\class2.cs:line 6
   at MyApp.Main() in d:\projects\test\class2.cs:line 18
Now you can see full exception stack trace.

November 28, 2004 06:21 PM | TrackBack | #.NET
Comments
Post a comment









Remember personal info?

    [Please replace < with &lt;]