This program is correct and does compile and run. But why does method 'a' not have a throws declaration?
class Exception1 {
public voi开发者_如何学编程d 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");
}
}
The problem is the return
in the finally
block:
Since the finally
will always be executed and it will always complete abruptly (either with an unchecked exception or with a return
), there is no way that the throw e
in the catch
-block (or any unchecked exception in the try
block) could ever be propagated downwards on the call stack.
If you remove the return
, then you'll notice that the compiler will not accept the code, stating that Exception
is not declared to be thrown on the method a()
.
ArrayIndexOutOfBoundsException is unchecked exception which means it is neither required to be declared nor catched explicitely.
So to put it simple. In java you have checked and unchecked exceptions (and Errors, lets leave them for now). Checked one extends Exception
and must be declared if thrown and handled if the code possibly throws them.
On the other hand unchecked exception extends RuntimeException
and it is not necessary to declare them and you are not required to handle them. NullPointerException
as an example. If you are required to handle them, you will need a lot of try catches since NPE can possibly happen on nearly any line of code.
精彩评论