简体   繁体   English

C# 重新抛出异常

[英]C# Re-throwing Exceptions

When throwing exceptions between multiple methods, should all methods re-throw the exception?在多个方法之间抛出异常时,所有方法都应该重新抛出异常吗? for example例如

Method1()
{
   Method2();
}

Method2()
{
   try
   {
      // Do something
   }
   catch
   {
      throw;
   }
}

try
{
   Method1();
}
catch
{
   // Do something about exception that was thrown from Method2()
}

Notice how in Method1() , I didn't need to wrap Method2() in a try block, should I be?请注意在Method1()中,我不需要将 Method2( Method2()包装在try块中,应该是吗?

You don't need to wrap everything in try blocks.您不需要将所有内容都包装在try块中。

You should only try when you want to catch something, and you should only catch something in the following cases:你应该只在你catch东西的时候try ,你应该只在以下情况下catch东西:

  • You're ready to handle the exception (do whatever needs to be done and don't let it propagate up the stack),您已准备好处理异常(做任何需要做的事情,不要让它传播到堆栈中),
  • You want to do something with the exception (eg log it) before rethrowing it (by using the parameterless form of throw ),您想在重新抛出异常之前对异常做一些事情(例如记录它)(通过使用throw的无参数形式),
  • You want to add details to the exception by wrapping it in another exception of your own (see Allon Guralnek's excellent comment below).您想通过将异常包装在您自己的另一个异常中来向异常添加详细信息(请参阅下面的 Allon Guralnek 的出色评论)。

You do not need to try, catch, and rethrow exceptions unless you have some particular reason for catching them in the first place.您不需要尝试、捕获和重新抛出异常,除非您有某些特殊原因首先要捕获它们。 Otherwise, they'll automatically get bubbled up from the lower level functions that throw them to the highest level function in your code.否则,它们会自动从较低级别的函数中冒泡,这些函数会将它们抛出到代码中的最高级别 function。 Essentially, you can think of them as getting "rethrown" all the way up, even though this isn't technically what is happening.从本质上讲,您可以将它们视为一直被“重新抛出”,即使这在技术上并不是正在发生的事情。

In fact, most of the time that you see a try / catch block written, it's incorrect.事实上,大多数时候你看到一个try / catch块被写入,它是不正确的。 You should not catch exceptions unless you can actually handle them.除非你能真正处理它们,否则你不应该捕获异常。 It's utterly pointless (and in fact considered to be bad practice) to catch exceptions just to rethrow them.捕获异常只是为了重新抛出它们是完全没有意义的(实际上被认为是不好的做法)。 Do not wrap all of your code within try blocks.不要将所有代码包装在try块中。

Note that by "handle them", I mean that your code in the catch block will take some specific action based on the particular exception that was thrown that attempts to correct the exceptional condition.请注意,通过“处理它们”,我的意思是您在catch块中的代码将根据抛出的尝试纠正异常情况的特定异常采取一些特定的操作。
For example, for a FileNotFoundException , you might inform the user that the file could not be found and ask them to choose another one.例如,对于FileNotFoundException ,您可能会通知用户找不到文件并要求他们选择另一个文件。

See my answer here for more detail and a thorough discussion of "exception handling best practices".有关“异常处理最佳实践”的更多详细信息和全面讨论,请参阅我的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM