Loading blog entries.. loading

Exception handling particulars in C#

Friday, July 8, 2011 3:22 PM
Written by Wayne Ye
Font Size: S  M  L 

Background

Exception handling appears in most .NET applications, this post is trying to describe some  Exception handling particulars in C# which might not take enough awareness from C# developers. 

Differences between throw and throw ex 

I guess every C# developer has seen code snippet below:

 try
{
    // Do some work, exception occurs
}
catch (IOException ex)
{
    // Exception caught, re-throw it to bubble up
    throw ex;
}

In the catch block, we can rethrow the caught exception instance of IOException to higher level, and we may also saw another way in a little different:

 try
{
    // Do some work, exception occurs
}
catch (IOException ex)
{
    // Exception caught, re-throw it to bubble up
    throw;
}

Is there any different? 

The answer is yes! To prove that I wrote a simple snippet of code below, first is a simple customized Exception: DummyException.

 internal class DummyException : Exception
{
    public DummyException(String dummymsg)
        : base(dummymsg)
    {

    }

    public DummyException(String dummymsg, Exception innerException)
        : base(dummymsg, innerException)
    {

    }
}

 And then I manually throw the DummyException within one method, while handle it in different way mentioned above:

 class Program
{
    private static void DoLowLevelOperation()
    {
        // Do some low level operation
        throw new DummyException("A dummy exception message!");
    }

    public static void MethodThrowException1()
    {
        try
        {
            DoLowLevelOperation();
        }
        catch (DummyException de)
        {
            throw;
        }
    }
    public static void MethodThrowException2()
    {
        try
        {
            DoLowLevelOperation();
        }
        catch (DummyException de)
        {
            throw de;
        }
    }

    static void Main(string[] args)
    {
        try
        {
            MethodThrowException1();
        }
        catch (DummyException de1)
        {
            Console.WriteLine(de1.Message);
            Console.WriteLine(de1.StackTrace);
        }

        try
        {
            MethodThrowException2();
        }
        catch (DummyException de2)
        {
            Console.WriteLine(de2.Message);
            Console.WriteLine(de2.StackTrace);
        }
    }
}

 The result will be:

Exception handling

So the difference is, "throw ex" will truncate the StackTrace information where it was originally thrown (this will cause the so called issue - "breaking the stack"), but "throw" will contain all the information.

Delve deeper, "throw ex" in IL level essentially indicates "rethrow", whereas "throw" indicate "throw", please see their IL code below:

 .method public hidebysig static void MethodThrowException1() cil managed
{
    .maxstack 1
    .locals init (
        [0] class ConsoleUnitTest.DummyException de)
    L_0000: nop
    L_0001: nop
    L_0002: call void ConsoleUnitTest.Program::DoLowLevelOperation()
    L_0007: nop
    L_0008: nop
    L_0009: leave.s L_000f
    L_000b: stloc.0
    L_000c: nop
    L_000d: rethrow
    L_000f: nop
    L_0010: ret
    .try L_0001 to L_000b catch ConsoleUnitTest.DummyException handler L_000b to L_000f
}
 .method public hidebysig static void MethodThrowException2() cil managed
{
    .maxstack 1
    .locals init (
        [0] class ConsoleUnitTest.DummyException de)
    L_0000: nop
    L_0001: nop
    L_0002: call void ConsoleUnitTest.Program::DoLowLevelOperation()
    L_0007: nop
    L_0008: nop
    L_0009: leave.s L_000f
    L_000b: stloc.0
    L_000c: nop
    L_000d: ldloc.0
    L_000e: throw
    L_000f: nop
    L_0010: ret
    .try L_0001 to L_000b catch ConsoleUnitTest.DummyException handler L_000b to L_000f
}

 The definition for "rethrow" and "throw" in IL are showing below:

rethrow: Rethrows the current exception.

throw: Throws the exception Object currently on evaluation stack.

So what should we do?

Now that we are clear about the difference, what should we do? Every time we manually throw a specific type of Exception, we should wrap the caught exception as InnerException:

 try
{
    throw new DummyException("A dummy exception message!");
}
catch (DummyException de)
{
    AnotherTypeOfException anotherTypeOfException = new AnotherTypeOfException("Customized exception message.", de)
    throw anotherTypeOfException;
}

When initializes AnotherTypeOfException we actually calls Exception's construcor "(String message, Exception innerException)", so finally there will be no information loss.

There is one particular details, when we wrote code similar with below, Resharper will warning us it is redundant, because "The catch statement may appear to be doing something, but it really isn't: all it's doing is throwing the exception (with the same stack information)", Resharper link

RedundantThrow1.png

RedundantThrow2.png  

Instead, if we wrote "throw de", in the above example, Resharper will NOT give you any warning, because now we know they are different, "throw de" will truncate the StackTrace information and rethrow the DemmyException instance

Different between parameterless catch and catch (Exception ex) 

Before .NET Framework 2.0, Non-CLS-Compliant exceptions does not inherit from System.Exception, that means catch (Exception ex) cannot catch Non-CLS-Compliant exceptions thrown from for example COM or native C++ components; However, in .NET Framework 2.0, compiler will wrap those Non-CLS-Compliant exceptions into an specific Exception type: RuntimeWrappedException, it has a property: WrappedException to store a non-CLS-Compliant exception, results in statement "catch (Exception ex)" can catch all runtime exceptions.

Whereas this is configurable, the wrapping operation is by default on how ever could be turn off be applying RuntimeCompatibility attribute to your assembly, i.e. AssemblyInfo.cs.

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = false)]

By specifying WrapNonExceptionThrows = false under RuntimeCompatibility attribute, Non-CLS-Compliant exceptions will not be converted to System.Exception, so they will not be caught by catch (Exception ex) but can be caught by parameterless catch.  

Further reading  

Exception Handling on MSDN
http://msdn.microsoft.com/en-us/library/ms229005.aspx

Using COM Object
http://insideaspnet.com/index/using-com-objects/ 

Difference between "throw" and "throw ex" in .NET
http://geekswithblogs.net/sdorman/archive/2007/08/20/Difference-between-quotthrowquot-and-quotthrow-exquot-in-.NET.aspx

Also posted at my blog - Wayne's Geek Life: 
http://wayneye.com/Blog/Different-Between-Throw-Throw-EX  

Also posted on CodeProject: http://www.codeproject.com/Articles/228868/Different-between-throw-and-throw-ex

 

Permalink: http://wayneye.com/Blog/Exception-Handling-Particulars-In-Csharp 2929 Views  2 Comments
Tag: Category:Programming».Net Framework»Essence

 

 


↓Comments↓

  changeswayWednesday, November 14, 2012 5:44 PM
I find u form codeproject when I search something about how to use google latitude on a WinCE device with somekind of GPRS modem. Ur blog with full english shocked me a lot, u give me a example that we can study the details deeply. Tks ur contribution and the free code!
 
  WayneFriday, November 16, 2012 8:25 PM
@changesway You are welcome and thank you for leaving a comment on my blog:)
 

Your view point or opinion?
Nickname *
 
Gravatar *
Required (not shown), used only for displaying Gravatar and receiving future notification when new comment(s) posted on this blog.
 
Website/Blog
 
Content *
Current length:     Maximum allowed: charactors