File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Exception within method with return value Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exception within method with return value" Watch "Exception within method with return value" New topic
Author

Exception within method with return value

Roger Zhao
Ranch Hand

Joined: Aug 05, 2003
Posts: 73
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!


"There is a will,there is a way!"<br />SCJP1.4
Cody Beth
Greenhorn

Joined: May 20, 2002
Posts: 11
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

Joined: Aug 05, 2003
Posts: 73
It seems all are based on the mechanism of Java.
For me, More clear than before !
Thanks a lot!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exception within method with return value