这个程序是正确的,可以编译和运行。但是为什么方法'a‘没有抛出声明呢?
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");
}
}发布于 2011-05-11 16:34:13
问题出在finally块中的return:
由于finally将始终执行,并且总是突然完成(带有未检查的异常或return),因此catch-block中的throw e (或try块中的任何未检查的异常)无法在调用堆栈上向下传播。
如果您删除了return,那么您会注意到编译器不会接受代码,说明Exception没有声明为在a()方法上抛出。
发布于 2011-05-11 16:19:45
ArrayIndexOutOfBoundsException是未检查的异常,这意味着它既不需要声明,也不需要显式捕获。
所以简单的说。在java中,你有检查过的和未检查过的异常(和错误,让我们暂时不去管它们)。Checked one扩展Exception,如果抛出则必须声明,如果代码可能抛出它们,则必须对其进行处理。
另一方面,未检查的异常扩展了RuntimeException,不需要声明它们,也不需要处理它们。以NullPointerException为例。如果您需要处理它们,您将需要大量的try catches,因为NPE可能发生在几乎任何代码行上。
https://stackoverflow.com/questions/5961227
复制相似问题