Search code examples
javaexceptionreturninfinite-loop

Compilation and return values of infinite loops with try-catch blocks


I encountered this problem when experimenting with file I/O. This method compiles:

public static int testMethod1() {
        try {
            while (true);
        } catch (Exception e) {
            return 0;
        }
        
    }

While these two do not:

public static int testMethod2() {
        try {
            while (true) { break; }
        } catch (Exception e) {
            return 0;
        }
        
    }
public static int testMethod3() {
        try {
            while (true) {
                if (false) {
                    break;                  
                }
            }
        } catch (Exception e) {
            return 0;
        }
        
    }

I cannot wrap my head around this. The first method is logically equivalent to the third. What is the compiler doing exactly?


Solution

  • The first method is logically equivalent to the third

    It is not. The if(false) does make a difference. The compiler does not evaluate this at compile time, thus it is possible for the code to reach the break, in which case you don't return anything (just like in the second snippet), which is the actual compilation error.

    For more infomation regarding if(false), take a look at the JLS, which states all the way at the bottom:

    The rationale for this differing treatment is to allow programmers to define "flag variables" such as: static final boolean DEBUG = false; and then write code such as: if (DEBUG) { x=3; }