This program is correct and does compile and run. But why does method ‘a’ not have a throws declaration?
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");
}
}
The problem is the
returnin thefinallyblock:Since the
finallywill always be executed and it will always complete abruptly (either with an unchecked exception or with areturn), there is no way that thethrow ein thecatch-block (or any unchecked exception in thetryblock) 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 thatExceptionis not declared to be thrown on the methoda().