• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

return and try/catch/finally

 
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For the following two programs, suppose file Hello.txt doesn't exist.
//program 1:
import java.io.*;
public class TryCatchTest2 {
public static void main(String[] args) {
TryCatchTest2 t=new TryCatchTest2();
System.out.println(t.amethod());
}
public int amethod() {
try {
FileInputStream fis=new FileInputStream("Hello.txt");
}
catch (IOException e) {
System.out.println("catch");
return 2;
}
finally {
System.out.println("finally");
}
return 1;
}
}
Putput:
catch
finally
2
//program 2
import java.io.*;
public class TryCatchTest2 {
public static void main(String[] args) {
TryCatchTest2 t=new TryCatchTest2();
System.out.println(t.amethod());
}
public int amethod() {
try {
FileInputStream fis=new FileInputStream("Hello.txt");
}
catch (IOException e) {
System.out.println("catch");
return 2;
}
finally {
System.out.println("finally");
return 1;
}
}
}
output:
catch
finally
1
Can somebody explain why program 1 return 2, not 1? If the checked exception is caught and after finally block, the rest of the method should be executed, right?
 
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Bin,
You are missing the line:
return 2;
that is inside your catch block. This is the return that is getting executed after the finally block. This is because the JVM guarantees that the finally block will be executed before the method will exit. Since the above statement will cause the method to exit the JVM will execute the finally section before executing the method that originally caused the method to exit.
Regards,
Manfred.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic