File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception within method with return value

 
Roger Zhao
Ranch Hand
Posts: 73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,all:
Another question:
import java.io.*;
public class test{
public static void main(String argv[]){
test m = new test();
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; /*
}
finally{
System.out.println("Doing finally"); }

System.out.println("Return 0"); //#
return 0; //#
}
}
Output:No such file found
    Doing finally
    -1 // why not 0 ?
The statements marked "//#" didn't execute ? why?
Thanks!
 
Cody Beth
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Roger,
The flow in amethod() is as follows:
1) FileNotFoundException is raised in the try block,so code in the catch block is executed.
and hence the "No such file found" is printed.
2) And finally block which is part of try-catch-fianlly will be executed just before return statement in the catch block is called.
and hence "Doing finally" is printed.

3) After this execution exits the amethod() (because of return statment in catch block)and -1 is returned to main method.And hence the code after try-catch-finally is not executed

If we comment the return statement from catch block .Then code will execute the //# statements as well.
I hope this clears ur doubt.
 
Roger Zhao
Ranch Hand
Posts: 73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It seems all are based on the mechanism of Java.
For me, More clear than before !
Thanks a lot!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic