我正在阅读 C# 文章。它表明
在 catch block 的末尾,您有三个选择:
<我>
• 重新抛出相同的异常,通知
的调用堆栈中更高层的代码
异常。
• 抛出不同的异常,为更高层的代码提供更丰富的异常信息 调用栈。
• 让线程从 catch block 的底部掉出来。
我无法理解这些要点。如果你能通过简单的例子来阐明它,那将是一个很大的帮助。
提前致谢。
更新: 当我需要处理重新抛出的异常时,我是否需要像
这样的嵌套 try .. catch blocktry
{
try
{
}
catch(InvalidOperationException exp)
{
throw;
}
}
catch(Exception ex)
{
// handle the exception thrown by inner catch block
// (in this case the "throw" clause inside the inner "catch")
}
}
最佳答案
好吧,下面是代码中的那些不同选项:
选项 1:重新抛出
try
{
// Something
}
catch (IOException e)
{
// Do some logging first
throw;
}
选项 2:抛出不同的异常
try
{
// Something
}
catch (IOException e)
{
// Do some logging first
throw new SorryDaveICantDoThatException("Oops", e);
}
方案三:让线从底部掉出来
try
{
// Something
}
catch (IOException e)
{
// Possibly do some logging, and handle the problem.
// No need to throw, I've handled it
}
编辑:要回答额外的问题,是的 - 如果您需要处理重新抛出的异常,则需要在外部范围内处理,正如问题中所示。但这很少是个好主意。事实上,catch
block 本来就应该相对少见,嵌套 block 更是如此。
关于c# - 捕获 block 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1530374/