繁体   English   中英

重新抛出异常并再次捕获

[英]Rethrow Exception and Catch Again

我正在使用C#,想知道是否有可能从try/catch抛出异常并让以后的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 {
    //...
}

仅当您的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..
     }
   }

您的代码应该可以工作,但是真正的问题是应该使用异常来通知外部代码部分有关这一事实的信息,即出了问题。 在try部分中手动抛出异常并在随后的catch部分中捕获它是毫无意义的。 如果您知道无法处理某些IO操作,请使用if-else语句立即进行处理。 为此,使用try-catch无疑是一种不好的,无效的做法。

不确定(由于变量范围,因为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)
{
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM