How to exit if and try/catch and branch elsewhere (like a goto) in Java?

565 Views Asked by At

Is it possible to improve this Java code by not using labels (and not repeating too much code or creating too many methods)?

void func() {

    Object r;
    Object s;

    if (r == null ) {
        try { some code 1 modifying the value of s; }
        catch (Exception e) {
            some code 2;
            break lab1;
        }

        if ( s == null ) {
            some code 3;
            break lab2
        }       
    }   

    lab1:
        some code 4;
    lab2:
        some code 5;
}

Edit:

I made a mistake using break/label. I used them like a goto (code after lab1 must be executed also if r!=null. This is not their purpose, and such code cannot compile because the break cannot reference a label forward. I understand there is no goto equivalent (a statement that can branch anywhere) in Java.

I wrote the code using a custom Exception1 that forces the outer if to be exited:

try {
    if (r!=null) {
        throws new Exception1();
    }

    try { some code 1; }
    catch (Exception e1) {
        some code 2;
        throws new Exception1();
    }
    if (s == null) {
        some code 3;
    }
}    
catch (Exception1 e2) { some code 4; }

some code 5;

This would not be a winner at a code-fashion contest, but at least it works. Thanks for your answers and comments.

3

There are 3 best solutions below

0
On BEST ANSWER
try {
    Object data;
    // Processing
    if (data == null) {
        throw new NullPointerException();
    }
} catch (Exception exception) {
    // Unique code
}
1
On
void func() {

    Object r;
    Object s;

    if (r == null ) {
        try { some code 1 modifying the value of s; }
        catch (Exception e) {
            some code 2;
            some code 4;
            return;
        }

        if ( s == null ) {
            some code 3;
            some code 5;
            return; //not necessary if there's no code after this.
        }       
    }   
}
1
On
void func() {
    Object r;
    Object s;

    if (r == null ) {
        try { 
            some code 1 modifying the value of s; 
            if ( s == null ) {
                some code 3;
                some code 5;
            } 
        } catch (Exception e) {
            some code 2;
            some code 4;
        }
    }   
}