Rethrow例外和再次捕获

时间:2014-07-08 13:38:29

标签: c# exception exception-handling

我正在使用C#并想知道是否有可能从try/catch重新抛出异常,并且稍后有catch语句重新发送它?

try {
// 1. Try some operation
    //Failed operations

// 2. Throw an exception
    throw new IOException("I tried my best");
} catch(IOException) {
// 3. Try some specific recovery operation
    //Failed operations

//4. Rethrow and try again
    throw;
}

... Some more specific exception handlers

} catch(Exception) {
// 5. Re-caught here as a last-ditch effort, generic recovery operation
    //Process here
} finally {
    //...
}

3 个答案:

答案 0 :(得分:3)

仅当您的catch语句抛出另一个try / catch时,例如:

try{

    ...

   try{
        ...
   }
   catch(ExceptionA a)
   {
      throw;
   }
   catch(Exception e)
   {
       //will not not catch ExceptionA (rethrow or not)
   }
}
catch(ExceptionA a)
{
    //this would catch the re-throw
}
catch( Exception e)
{
}

相反,为什么不抓住一般Exception然后判断异常类型?

try{
        ...
   }
   catch(Exception e)
   {
       if (e is ExceptionA){
            ...
       }
   }

或者在finally

上加上逻辑
 System.Exception thrownException = null;
 try{
        ...
   }
   catch( ExceptionA a)
   {
      thrownException = a;
      ...  // do special handling...
   }
   catch( ExceptionB b)
   {
      thrownException = b;
      ...  // do special handling...
   }
   catch(Exception e)
   {
      ...
   }
   finally{
     if ( thrownException != null ) {
          ...   //case the type here or use some other way to identify..
     }
   }

答案 1 :(得分:-1)

您的代码应该可以工作,但真正的问题是应该使用异常来通知外部代码部分有关事实,即出现问题。在try部分手动抛出异常并在下面的catch部分中捕获它是没有意义的。如果您知道无法处理某些IO操作,请立即使用if-else语句处理它。使用try-catch毫无疑问是一种糟糕,低效的做法。

答案 2 :(得分:-2)

不确定(因为变量范围,因为c#不是我现在使用的语言,并且由于新添加的变量可能产生副作用,并且因为它看起来不是一个好的编码练习),但是会有效:

try{
     ...
}
catch(ExceptionA a)
{
   exception = a;  // "Store" the exception in a variable
}
catch(Exception e)
{
    //will not not catch ExceptionA (rethrow or not)
}

try
{
    if (exception)
        throw exception;  // kind of rethrow if variable is set
}
catch(ExceptionA a)
{
    //this would catch the re-throw
}
catch( Exception e)
{
}