2008-12-12 85 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块中的旧内容的情况。它可能适合你想要的更好,但也可能不会。