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?