我对基本的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!");
}
}
谢谢StrixVaria a nd Veger昨天快速回答! – user2127664 2013-03-06 17:42:59