javaif-statementlabeltry-catchcode-maintainability

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


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.


Solution

  • try {
        Object data;
        // Processing
        if (data == null) {
            throw new NullPointerException();
        }
    } catch (Exception exception) {
        // Unique code
    }