Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exception" Watch "Exception" New topic
Author

Exception

Vinal Kalyan
Greenhorn

Joined: Feb 01, 2005
Posts: 3
Can you please explain why the exception in a() is not thrown up the call Stack and caught by the catch block in the main method. Instead, the method returns the Integer object and no exception is caught in the main method.

Class Test {
public static void main(String[] args) {
try {
Object obj = a();

catch (Exception e) {
System.out.println(e);
}

}
}

static Object a() throws Exception {
try {
throw new IOException();
}
catch (IOException e) {
throw e;
}
finally {
return new Integer(1);
}
}
}

Thanks

Vinal.
Akash Singhal
Greenhorn

Joined: Feb 12, 2005
Posts: 11
The return from the finally block overrides any previous return values as well as it also overrides any exceptions thrown. Hence the exception thrown is overriden by the object returned from the finally Block..

Regards
Animesh Shrivastava
Ranch Hand

Joined: Jul 19, 2004
Posts: 298
Related to the same question i have a small doubt:
If i change the method Object a() as:

Why am i not getting any compilation errors? shouldnt the method return something of type Object?

thanks
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by Animesh Shrivastava:
Why am i not getting any compilation errors? shouldnt the method return something of type Object?
In this case the compiler can determine that an exception is always thrown from this code. Any statement after the try-catch block is unreachable under all conditions, so there's no need for a return.
 
 
subject: Exception