Unreachable statement in Java
2 min readJun 30, 2024
Today i was doing a small pet project in Java, and seen the following paradox. The following code:
import java.io.FileInputStream;
import java.io.IOException;
public class Example {
public static boolean run() {
try {
FileInputStream fis = new FileInputStream("/noSuchFileExists");
return true;
} catch (IOException ioe) {
System.out.println(ioe.toString());
System.exit(1);
return false;
}
}
public static void main(String[] args) {
System.out.println(run());
}
}
compiled correctly, even though the return false
statement will never be executed, simply because System.exit(1)
terminates the program. Funny isn't it? The results of an execution verified my initial suspicions.
nefarian:~ bkarak$ java Example
java.io.FileNotFoundException: /noSuchFileExists (No such file or directory)
And a decompilation of the class produced:
Compiled from "Example.java"
public class Example extends java.lang.Object{
public Example();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return
public static boolean run();
Code:
0: new #2; //class java/io/FileInputStream
3: dup
4: ldc #3; //String /noSuchFileExists
6: invokespecial…