File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Confusion in Exception Question from Marcus Green Exam 1 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 "Confusion in Exception Question from Marcus Green Exam 1" Watch "Confusion in Exception Question from Marcus Green Exam 1" New topic

Confusion in Exception Question from Marcus Green Exam 1

Karthik Balasubramanian
Ranch Hand

Joined: Dec 13, 2002
Posts: 43
Please look at the code.
What will be output if you try to compile and run the following code, but there is
no file called Hello.txt in the current directory?.
public class Mine {
public static void main(String argv[]){
Mine m=new Mine();
public int amethod()
try {
FileInputStream dis=new FileInputStream"Hello.txt");
catch (FileNotFoundException fne) { System.out.println("No such file found");
return -1;
catch(IOException ioe) {
System.out.println("Doing finally");
return 0;
1) No such file found
2 No such file found ,-1
3) No such file found, Doing finally, -1
4) 0
Answer is: No such File found, Doing Finally, -1.
My question is, how does this work? After an exception is caught, it prints the statement. The next statement is return -1. Will it not execute immediately? why are we getting this return value after "finally" executes?
What about the last statement "return 0"?why is this not getting executed?
Can anyone explain, what is the series of steps that happen, in this kind of situation.
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
Finally is always executed except for the case when System.exit is called. This includes:

a) Finally is executed if the try/catch clauses complete without an exception or returning. The next statement after finally is executed.
b) Finally is executed even if any Throwable is thrown. If there is a handler for it, it gets executed and then finally.
c) Finally is executed even if return is called either from try or from catch. Finally is executed before returning. In the example returning from return -1 will preclude the execution of return 0.
Summing up: finally is guaranteed to execute before any instruction attempting to leave off the flow of code for the set of try/catch. This termination of the flow of code can be normal, falling through the code; abnormal, throwing a Throwable; or simply returning. However System.exit() will prevent the execution of finally.

SCJP2. Please Indent your code using UBB Code
Sridhar Srikanthan
Ranch Hand

Joined: Jan 08, 2003
Posts: 366
Thanks Jose and kartik
because I always thought that it returns 0 instead of -1.
I agree. Here's the link:
subject: Confusion in Exception Question from Marcus Green Exam 1
jQuery in Action, 3rd edition