Contiuning Reading Java Language Specification turned to section Exceptions
Well can we predict the output of the following program?
class BlewIt extends Exception {
BlewIt() { }
BlewIt(String s) { super(s); }
}
class Test {
static void blowUp() throws BlewIt {
throw new BlewIt();
}
public static void main(String[] args) {
try {
blowUp();
} catch (RuntimeException r) {
System.out.println("RuntimeException:" + r);
} catch (BlewIt b) {
System.out.println("BlewIt");
}
}
}
Output: BlewIt
Reason:
The try-catch statement in the body of main has two catch clauses. The run-time type of the exception is BlewIt which is not assignable to a variable of type RuntimeException, but is assignable to a variable of type BlewIt, so the output of the example is: BlewIt
Now can we predict the output of this program?
public class CatchFinally {
public static void main(String[] args) {
try {
m1();
}catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
static void m1() throws Exception {
try {
int z=0;
int i=1/z;
}catch(Exception ex) {
throw new RuntimeException("RunTimeException");
}finally {
throw new Exception("Exception");
}
}
}
Output: Exception.
Why??????
Closely observe what JLS states about catch block and finally block.
"
If the catch block completes abruptly for reason R, then the finally block is executed. Then there is a choice:
If the finally block completes normally, then the try statement completes abruptly for reason R.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
"
Hence the throw in catch block is discarded.
Now replace the m1() function and try the output once again.
static void m1() throws Exception {
try {
int z=0;
int i=1/z;
FileInputStream str=new FileInputStream("junk");
}catch(IOException ex) {
throw new RuntimeException("RunTimeException");
}finally {
throw new Exception("Exception");
}
}
Reason:
If the run-time type of V is not assignable to the parameter of any catch clause of the try statement, then the finally block is executed. Then there is a choice:
If the finally block completes normally, then the try statement completes abruptly because of a throw of the value V.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten).
Always remember this keyword cannot be used in a static context.
Hope it helps and please let me know if any further explanation required.
Monday, 10 September 2007
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment