Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

c# - Catch vs Catch (Exception e) and Throw vs Throw e

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;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...