Exception Handling
public class Ex {
public int getX(int y) {
int k=27;
try{
k=k/y;
return k;
System.out.println("exception caught");
k=k/y;
// throw new ArithmeticException(); // Line 1
return k;
System.out.println("finally");
// k=k/y; // Line 2
return 5; // Line 3
}
}
public static void main(String args[]) {
Ex eh=new Ex();
System.out.println( eh.getX(0));
}
}
output:
exception caught
finally
5
Since the finally clause should execute no matter whether a new exception is thrown inside a catch block (or)Not the o/p "finally" is printed and
try commenting the return statement in finally block.
Ex.java:21: warning: finally clause cannot complete normally
}
^
1 warning
Note: If you check line 1 there is a new checked exception being thrown explicitly and if thats the case then the immediate next line will be unreacheable statement complained by the compiler. Hence no statement goes after an explicitly thrown exception(either Checked (or) UnChecked).
To stop the compiler from complaining about explicitly thrown checked exceptions either you should declare it in the throws clause (or) have a corresponding catch statement. But there is such no restriction for an unchecked exception.
Regarding Line 2
If line 2 and line 3 are commented
If a finally block contains a throw(Programatically (or) explicit throw statement) or return, these cause any previously-thrown exception to be discarded. However if the finally block does not throw an exception or return, then any uncaught exception from the try block (or) catch block will still be thrown after the finally completes.
Regarding Line 3
If line 3 is uncommented
There are differences between throwing a exception [ either explicitly (or) programatically ] and return statement in a finally block
The return statement nullifies any previous exception and makes sure the programs flow continues normally. Regarding a exception thrown inside a finally block even though it discards any previous exceptions( either is try block (or) catch block) still it generates a new exception and you will see a stack trace print during runtime.
0 Comments:
Post a Comment
<< Home