捕捉VS赶上(例外五)和投影VS投掷Ë [英] Catch vs Catch (Exception e) and Throw vs Throw e

查看:216
本文介绍了捕捉VS赶上(例外五)和投影VS投掷Ë的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是这两个code的例子一样吗? 赶上(例外五)有相同的输出,其结果也是相同的,如果我写的投掷Ë

主营:

 尝试
{
    一个();
    // B();
}
赶上(例外五)
{
    Console.WriteLine({0}异常捕获,E);
}

code 1:

 静态无效A()
{
    尝试
    {
        int值= 1 / int.Parse(0);
    }
    赶上(例外五)
    {
        Ë扔掉;
    }
}

code 2:

 静态无效A()
{
    //重新抛出的语法。
    尝试
    {
        int值= 1 / int.Parse(0);
    }
    抓住
    {
        扔;
    }
}


解决方案

我觉得这里有两个问题。


什么是之间的区别抛出扔Ë;

我不认为有是有史以来一个很好的理由写赶上(例外五){抛出Ë; } 。这失去了原来的堆栈跟踪。当您使用扔; 原来的堆栈跟踪是preserved。这是好事,因为这意味着错误的原因更容易找到。


之间有什么赶上(例外五) <区别/ p>

这两个你的例子是一样的,同样没用的 - 他们只是捕捉异常,然后再次抛出它。一个微小的差别是,第一个例子将产生一个编译器警告


  

变量'E'是声明,但从未使用过。


这更有意义,问这个问题,如果你在你的catch块,实际上做一些有用的东西有一些其他的code。例如,您可能要记录的异常:

 尝试
{
    int值= 1 / int.Parse(0);
}
赶上(例外五)
{
    LogException(E);
    扔;
}

现在有必要让你不得不捕获异常基准使用的第一个版本。

如果您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;
    }
}

解决方案

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.

这篇关于捕捉VS赶上(例外五)和投影VS投掷Ë的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆