Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confusion in Exception Question from Marcus Green Exam 1

 
Karthik Balasubramanian
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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?.
import java.io.*;
public class Mine {
public static void main(String argv[]){
Mine m=new Mine();
System.out.println(m.amethod());
}
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) {
}
finally{
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.
Karthik
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sridhar Srikanthan
Ranch Hand
Posts: 366
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jose and kartik
because I always thought that it returns 0 instead of -1.
Thanks
Sri
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic