2013-03-05 42 views
2

我对基本的Java练习测试问题做了回应,下面这个问题的正确答案在参加测试时滑过了我。未处理的Java异常执行方法的其余部分?

问题:“如果没有捕获到异常,finally块将会运行,并且方法的其余部分被跳过 - TRUE或FALSE?”

我试图证明ThrowTest类(粘贴在底部)的答案,但我发现Java异常处理有些陌生。我按照catch块的ArrayIndexOutOfBoundsException部分注释掉的那样编译类。然后我执行该类而不传递输入参数,从而创建一个异常(ArrayIndexOutOfBoundsException异常)。我期望最终的System.out.println不会执行,事实上它不会。

我发现如果我取消注释ArrayIndexOutOfBoundsException catch块并重新编译,该类会在运行时捕获该特定错误,并在底部执行“其余方法”println。那么,我的代码是否证明了“方法的其余部分被跳过”的其余部分,还是必须从主方法以外的方法来测试它?也许有一种更直接的测试方法。

public class ThrowTest 
{ 

    public static void main(String[] args) 
    { 
    try 
     { 
      String anyString = args[0]; 
      System.out.println("Try code executes"); 
     } 

    catch(SecurityException e) //any old exception 
     { 
      System.err.println ("Error: SecurityException. "); 
      e.printStackTrace(); 
     } 

    /* begin comment 
    catch(ArrayIndexOutOfBoundsException e) 
     { 
      System.err.println("Error: Caught ArrayIndexOutOfBoundsException. "); 
      e.printStackTrace();  
     } 
    end comment */ 

    finally 
     { 
      System.out.println("finally block executes!"); 
     } 

     System.out.println("Rest of method executes!"); 
    } 

} 

回答

0

您的代码确实证明了一切正如您所描述的那样。当你捕捉到一个异常时,这个方法的其余部分就会执行。如果让方法抛出异常,它的执行立即停止。无论哪种方式,finally块将始终执行。

+0

谢谢StrixVaria a nd Veger昨天快速回答! – user2127664 2013-03-06 17:42:59

1

无论是抛出finally块将始终执行(不包含任何奇怪的情况像内存不足)什么异常,因此给出以下

try { 
    // do some code 
} 
catch (SomeException e) { 
    // exception handling 
} 
finally { 
    doFinallyStuff(); 
} 

doOtherStuff(); 

doFinallyStuff会一直执行在这里。但doOtherStuff只会在下列条件下执行:

  • 没有异常抛出
  • SomeException被关上,如果另一个例外是在抛出的catch块不重新抛出异常链向上

try块不是由catch块处理,doFinallyStuff仍会执行,但doOtherStuff不会