簡體   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