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:
nefarian:~ bkarak$ javap Example -c Compiled from "Example.java" public class Example extends java.lang.Object{ public Example(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."This is a really funny situation. If you dont write the":()V 4: return public static boolean run(); Code: 0: new #2; //class java/io/FileInputStream 3: dup 4: ldc #3; //String /noSuchFileExists 6: invokespecial #4; //Method java/io/FileInputStream." ":(Ljava/lang/String;)V 9: astore_0 10: iconst_1 11: ireturn 12: astore_0 13: getstatic #6; //Field java/lang/System.out:Ljava/io/PrintStream; 16: aload_0 17: invokevirtual #7; //Method java/io/IOException.toString:()Ljava/lang/String; 20: invokevirtual #8; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 23: iconst_1 24: invokestatic #9; //Method java/lang/System.exit:(I)V 27: iconst_0 28: ireturn Exception table: from to target type 0 11 12 Class java/io/IOException public static void main(java.lang.String[]); Code: 0: getstatic #6; //Field java/lang/System.out:Ljava/io/PrintStream; 3: invokestatic #10; //Method run:()Z 6: invokevirtual #11; //Method java/io/PrintStream.println:(Z)V 9: return }
return false
statement,
the compiler will report and error.I dont really know if the compiler should handle this situation. Of course
System.exit(1)
is the only direct function that kills the jvm process, and probably the compiler should be aware of it.
Or it should not?