这个程序是正确的,可以编译运行。但为什么方法 'a' 没有 throws 声明?
class Exception1 {
public void a()
{
int array[] = new int[5];
try
{
System.out.println("Try");
array[10]=1;
}
catch (Exception e)
{
System.out.println("Exception");
throw e;
}
finally
{
System.out.println("Finally");
return;
}
}
public static void main(String[] args)
{
Exception1 e1 = new Exception1();
try {
e1.a();
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Catch");
}
System.out.println("End of main");
}
}
最佳答案
问题是 finally
block 中的 return
:
因为 finally
将总是被执行并且它会总是突然完成(有一个未经检查的异常或有一个返回
),catch
block 中的 throw e
是不可能的(或者 try
block 中的任何未经检查的异常)可以在调用堆栈上向下传播。
如果您删除 return
,您会注意到编译器将不会接受该代码,声明 Exception
未声明为在方法上抛出 a()
。
关于java - 没有抛出条款,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5961227/