Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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; }

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading