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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:11:41  来源:igfitidea点击:

Nested Try and Catch blocks

c#web-servicesexception

提问by Mathematics

I have nested try-catchblocks in a custom C# code for SharePoint. I want to execute the code in only one catchblock (the inner one) when the code inside the inner tryblock 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 catchin 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 catchwouldn't fire if the inner catchhandled the exception

catch如果内部catch处理异常,外部不会触发

If you want the outer catchto 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 catchwill not be triggered from the inner try {} catch {}

本质上,由于您现在拥有代码,因此catch不会从内部触发外部try {} catch {}