Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch vs Catch (Exception e) and Throw vs Throw e

Tags:

c#

try-catch

Are these two code examples the same? Catch and Catch (Exception e) have the same output, and the result is also the same if I write Throw or Throw e.

Main:

try
{
    A();
    //B();
}
catch (Exception e)
{
    Console.WriteLine("{0} exception caught.", e);
}

Code 1:

static void A()
{
    try
    {
        int value = 1 / int.Parse("0");
    }
    catch (Exception e)
    {
        throw e;
    }
}

Code 2:

static void A()
{
    // Rethrow syntax.
    try
    {
        int value = 1 / int.Parse("0");
    }
    catch
    {
        throw;
    }
}
like image 308
a1204773 Avatar asked May 29 '12 20:05

a1204773


2 Answers

I think there are two questions here.


What is the difference between throw and throw e;?

I don't think there is ever a good reason to write catch (Exception e) { throw e; }. This loses the original stacktrace. When you use throw; the original stacktrace is preserved. This is good because it means that the cause of the error is easier to find.


What is the difference between catch and catch (Exception e)?

Both of your examples are the same and equally useless - they just catch an exception and then rethrow it. One minor difference is that the first example will generate a compiler warning.

The variable 'e' is declared but never used

It makes more sense to ask this question if you had some other code in your catch block that actually does something useful. For example you might want to log the exception:

try
{
    int value = 1 / int.Parse("0");
}
catch (Exception e)
{
    LogException(e);
    throw;
}

Now it's necessary to use the first version so that you have a reference to the caught exception.

If your catch block doesn't actually use the exception then you would want to use the second version to avoid the compiler warning.

like image 133
Mark Byers Avatar answered Nov 15 '22 04:11

Mark Byers


If we ignore the "unused variable" warning, the only time there is a practical difference between

catch {...}

and

catch(Exception ex) {...}

is when some non-C# code is throwing a non-Exception exception. C++ can throw anything. In .NET 1.1, you had to use catch (no (Exception ex)) to handle these unusual exceptions. However, this was problematic - not least, you can't see what was thrown! So in .NET 2.0 and above this is wrapped by default, so even if C++ throws, say, a string - you see it as an Exception subclass. Note that this can be disabled via a configuration setting, but: don't. Leave it alone!

The issue of throw; vs throw ex; is already mentioned, and relates to stack-traces. You can use throw in both cases, causing the original stack-trace to be preserved.

like image 37
Marc Gravell Avatar answered Nov 15 '22 04:11

Marc Gravell