【问题标题】:What does "throw;" by itself do? [duplicate]"投掷;" 是什么意思?靠自己做什么? [复制]
【发布时间】:2010-04-28 10:33:25
【问题描述】:

可能重复:
difference between throw and throw new Exception()

拥有的意义何在

catch (Exception)
{
    throw;
}

这是做什么的?

【问题讨论】:

标签: c# .net exception


【解决方案1】:

throw 关键字本身只是重新引发上面catch 语句捕获的异常。如果您想进行一些基本的异常处理(可能是诸如回滚事务之类的补偿操作)然后将异常重新抛出到调用方法,这很方便。

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

【讨论】:

  • 据我了解,catch 块的全部内容是throw;,所以没有额外的异常处理。不过,我可能错了。
  • 你对鲍里斯的观点有何回应?
  • Boris 是对的,提供的示例实际上并没有做任何事情,但我认为调用堆栈没有任何变化。
  • +1 用于解释原始调用堆栈保存,非常重要!
  • @Craig 和马特。你是对的,我很困惑(在我的回答中解释得更详细)
【解决方案2】:

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

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);
}

【讨论】:

  • +1 因为新的 throw 传递了原始异常 - 非常非常重要 (-:
【解决方案3】:

我能想到的唯一原因是如果您想在调试期间在此处放置一个断点。
我认为这也是一些工具生成的默认代码。

【讨论】:

    【解决方案4】:

    它会重新抛出完全相同的错误,您不会因此获得任何收益。
    有时您可以使用 catch 方法进行一些日志记录或其他操作,而不会像这样中断您的异常:

    catch (Exception) {
      myLogger.Log(LogLevels.Exception, "oh noes!")
      throw; 
    }
    

    我最初错误地认为这会释放你的筹码,但只有当你执行以下操作时才会这样做:

    catch (Exception err) {
      throw err; 
    }
    

    【讨论】:

    • 你确定你有额外的堆栈展开,因为单独使用“throw”只会重新抛出原来的异常,堆栈跟踪与原来的完全相同......对吧?!
    • @boris:你是说有些代码会被执行两次?
    • @Veggerby:你说得对,我对你所说的 catch(Exception ex){throw ex} 的情况感到困惑。在问题代码的情况下,什么都没有发生。 @Craig:没有什么会被执行两次
    【解决方案5】:

    只需重新抛出当前异常,该异常就会保留其“源”和堆栈跟踪。

    【讨论】:

      猜你喜欢
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      • 2013-03-10
      • 2014-04-03
      • 2011-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多