This program is correct and compiles and runs. But why doesn't the 'a' method 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 in returnthe block finally:
return
finally
Since it finallywill always execute, and it will always terminate abruptly (either with an unchecked exception or using return), there is no way that throw ein catch-block (or any exception thrown in a block try) can ever propagate down the call stack.
throw e
catch
try
If you delete return, you will notice that the compiler will not accept the code, stating that it is Exceptionnot declared thrown on the method a().
Exception
a()
ArrayIndexOutOfBoundsException - , , .
, . java ( , ). , Exception , , , , .
, RuntimeException, , . NullPointerException . , , NPE .
RuntimeException
NullPointerException