什么"扔"; 靠自己呢?

CJ7*_*CJ7 66 .net c# exception

可能重复:
throw和throw之间的差异新异常()

有什么意义

catch (Exception)
{
    throw;
}
Run Code Online (Sandbox Code Playgroud)

这是做什么的?

Mat*_*ton 98

throw关键字本身只是重新引发上述catch语句捕获的异常.如果你想做一些基本的异常处理(可能是回滚事务的补偿操作),然后重新抛出调用方法的异常,这很方便.

与捕获变量中的异常并抛出该实例相比,此方法具有一个显着优势:它保留了原始调用堆栈.如果你捕获(Exception ex)然后抛出ex,你的调用堆栈将只从那个throw语句开始,你将丢失原始错误的方法/行.

  • +1用于解释原始调用堆栈保存,非常重要! (2认同)

dcp*_*dcp 13

有时你可能想做这样的事情:

try
{
    // do some stuff that could cause SomeCustomException to happen, as 
    // well as other exceptions
}
catch (SomeCustomException)
{
    // this is here so we don't double wrap the exception, since
    // we know the exception is already SomeCustomException
    throw;
}
catch (Exception e)
{
    // we got some other exception, but we want all exceptions
    // thrown from this method to be SomeCustomException, so we wrap
    // it
    throw new SomeCustomException("An error occurred saving the widget", e);
}
Run Code Online (Sandbox Code Playgroud)

  • +1因为新的抛出传递了原始异常 - 非常非常重要( - : (3认同)