嵌套的Try和Catch块

时间:2013-09-13 09:57:47

标签: c# web-services exception

我在SharePoint的自定义C#代码中嵌套了try-catch块。当内部catch块内的代码抛出异常时,我只想在一个try块(内部块)中执行代码。

try
{
 //do something

   try
   {
        //do something              if exception is thrown, don't go to parent catch

   }
   catch(Exception ex) {...}

}
catch(Exception ex)
{ .... }

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

摘要

如果发生异常,除了内部catch之外,我不希望它到达父catch

2 个答案:

答案 0 :(得分:25)

如果您不想在这种情况下执行外部异常,则不应该从内部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
}

答案 1 :(得分:12)

如果内部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
}

基本上,正如您现在拥有代码一样,外部catch将不会从内部try {} catch {}

触发