August 06, 2013

Exception handling: The difference between 'throw' and 'throw exception'

There is a huge difference in how you handle exceptions and perhaps you do not even notice it.

The following two blocks of code looks almost the same - but they are quite different.

catch (Exception ex)
{
     throw ex;
}

catch (Exception)
{
     throw;
}

Try it out

Create a console application and use the following code.

using System;
 
class Program
{
    static void Main(string[] args)
    {
        try
        {
            CallFailingMethodAndPassException();
        }
        catch (Exception ex)
        {
            Console.WriteLine("\nStackTrace for method with 'Throw':");
            Console.WriteLine(ex.StackTrace);
        }
 
        try
        {
            CallFailingMethodAndThrowException();
        }
        catch (Exception ex)
        {
            Console.WriteLine("\nStackTrace for method with 'Throw ex':");
            Console.WriteLine(ex.StackTrace);
        }
 
        Console.ReadKey();
    }
 
    static void CallFailingMethodAndPassException()
    {
        try
        {
            CallFailingMethod();
        }
        catch (Exception)
        {
            throw;
        }
    }
 
    static void CallFailingMethodAndThrowException()
    {
        try
        {
            CallFailingMethod();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    static void CallFailingMethod()
    {
        FailingMethod();
    }
 
    static void FailingMethod()
    {
        throw new Exception("Throw an Exception");
    }
}

The result is as follows:

StackTrace for method with 'Throw':
at Program.FailingMethod() in c:\Code\POC\Exceptions\ConsoleApp\ConsoleApp\Program.cs:line 61
at Program.CallFailingMethod() in c:\Code\POC\Exceptions\ConsoleApp\ConsoleApp\Program.cs:line 56
at Program.CallFailingMethodAndPassException() in c:\Code\POC\Exceptions\ConsoleApp\ConsoleApp\Program.cs:line 38
at Program.Main(String[] args) in c:\Code\POC\Exceptions\ConsoleApp\ConsoleApp\Program.cs:line 9

StackTrace for method with 'Throw ex':
at Program.CallFailingMethodAndThrowException() in c:\Code\POC\Exceptions\ConsoleApp\ConsoleApp\Program.cs:line 50
at Program.Main(String[] args) in c:\Code\POC\Exceptions\ConsoleApp\ConsoleApp\Program.cs:line 19

As you can see the first method call returns the full stacktrace and the second method call only returns a partial stacktrace. So consider carefully how you handle exceptions in your code.

No comments:

Post a Comment