开发者

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 abo开发者_StackOverflowut exception that was thrown from Method2()
}

Notice how in Method1(), I didn't need to wrap Method2() in a try block, should I be?


You don't need to wrap everything in try blocks.

You should only try when you want to catch something, and you should only catch something in the following cases:

  • 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 (e.g. log it) before rethrowing it (by using the parameterless form of 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).


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. 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. 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.

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.
For example, for a FileNotFoundException, you might inform the user that the file could not be found and ask them to choose another one.

See my answer here for more detail and a thorough discussion of "exception handling best practices".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜