Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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.
 
Without deviation from the norm, progress is not possible - Zappa. Tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic