嵌套的Try和Catch块

Mat*_*ics 22 c# web-services 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)
{ .... }
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用不同类型的例外,但这不是我想要的.

摘要

如果出现异常,我不希望它达到的父母catch除了内catch.

Sac*_*hin 26

如果您不想在这种情况下执行外部异常,则不应从内部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
}
Run Code Online (Sandbox Code Playgroud)


iab*_*ott 13

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

如果你想要外部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
}
Run Code Online (Sandbox Code Playgroud)

基本上,当你现在有代码时,外部catch不会从内部触发try {} catch {}

  • 对于提问者的信用,我有同样的问题。它是这样的:在 Android 上使用 .Net PCL/Xamarin。在内部调用带有 try/catch 的异步方法。让它调用另一个异步方法,并且在单个调用中尝试/捕获。那个调用失败了。内部 try/catch 不会捕获,即使它是捕获(异常前)。外部 try/catch 得到它,但为时已晚。我怀疑在某些 VM 中,实际上不支持嵌套的 try/catch。 (2认同)