C# 嵌套的 Try 和 Catch 块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18783427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nested Try and Catch blocks
提问by Mathematics
I have nested try-catch
blocks in a custom C# code for SharePoint. I want to execute the code in only one catch
block (the inner one) when the code inside the inner try
block throws an exception.
我try-catch
在 SharePoint 的自定义 C# 代码中嵌套了块。catch
当内部try
块中的代码抛出异常时,我只想在一个块(内部块)中执行代码。
try
{
//do something
try
{
//do something if exception is thrown, don't go to parent catch
}
catch(Exception ex) {...}
}
catch(Exception ex)
{ .... }
I know I can use different types of exceptions but that's not what I am looking for.
我知道我可以使用不同类型的异常,但这不是我想要的。
Summary
概括
If exception occurs, I don't want it to reach the parent catch
in addition to the inner catch
.
如果发生异常,catch
除了内部catch
.
采纳答案by Sachin
If you don't want to execute the outer exception in that case you should not throw the exception from the inner catch block.
如果在这种情况下不想执行外部异常,则不应从内部 catch 块抛出异常。
try
{
//do something
try
{
//do something IF EXCEPTION HAPPENs don't Go to parent catch
}
catch(Exception ex)
{
// logging and don't use "throw" here.
}
}
catch(Exception ex)
{
// outer logging
}
回答by iabbott
The outer catch
wouldn't fire if the inner catch
handled the exception
catch
如果内部catch
处理异常,外部不会触发
If you want the outer catch
to fire as well, you'd have to do:
如果您还想让外部catch
火力,则必须执行以下操作:
try
{
//do something
try
{
//do something
}
catch(Exception ex)
{
// do some logging etc...
throw;
}
}
catch(Exception ex)
{
// now this will be triggered and you have
// the stack trace from the inner exception as well
}
Essentially, as you have the code there now, the outer catch
will not be triggered from the inner try {} catch {}
本质上,由于您现在拥有代码,因此catch
不会从内部触发外部try {} catch {}