2008-12-12 62 views
1

我有以下代碼try catch塊

Try 
    'Some code that causes exception 
Catch ex as ExceptionType1 
    'Handle Section - 1 
Catch ex as ExceptionType2 
    'Handle section - 2 
Catch ex as ExceptionType3 
    'Handle section - 3  
Finally 
    ' Clean up 
End Try 

假設ExceptionType1由被第處理的代碼引發 - 1,在部分1,我能得到控制傳遞給部-2處理後/部分-3?那可能嗎?

+0

你能發佈爲什麼你想這樣做的目的? – shahkalpesh 2008-12-12 20:09:59

回答

9

更改代碼以捕獲一個塊中的所有異常並確定類型和執行路徑。

1

我想你可以得到你想要的行爲,如果你做嵌套的嘗試塊。一旦拋出異常,執行到catch塊。如果沒有什麼是重新生成的,它最終會繼續。

3

您可以在異常處理程序中調用函數。

Try 
'Some code that causes exception' 
Catch ex as ExceptionType1 
    handler_1() 
    handler_2() 
    handler_3() 
Catch ex as ExceptionType2 
    handler_2() 
    handler_3() 
Catch ex as ExceptionType3 
    handler_3() 
Finally 
    handler_4()  
End Try 
2

您還沒有指定一個語言 ,我不知道的語言,所以我一般回答。

你不能那樣做。如果你想擁有共同的代碼,把它放到finally中,或者只需要爲某些捕獲的案例執行,你可以將代碼複製到相應的案例中。如果代碼更大並且您想避免冗餘,則可以將其放入其自己的函數中。如果這會降低代碼的可讀性,可以嵌套try/catch塊(至少在Java和C++中,我不知道你的語言)。這是Java中的例子:

class ThrowingException { 
    public static void main(String... args) { 
     try { 
      try { 
       throw new RuntimeException(); 
      } catch(RuntimeException e) { 
       System.out.println("Hi 1, handling RuntimeException.."); 
       throw e; 
      } finally { 
       System.out.println("finally 1"); 
      } 
     } catch(Exception e) { 
      System.out.println("Hi 2, handling Exception.."); 
     } finally { 
      System.out.println("finally 2"); 
     } 
    } 
} 

這將打印出:

Hi 1, handling RuntimeException.. 
finally 1 
Hi 2, handling Exception.. 
finally 2 

把你的普通代碼外catch塊。使用嵌套版本進行處理也可以處理髮生異常而不顯式重新拋出catch塊中的舊內容的情況。它可能適合你想要的更好,但也可能不會。