0

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.

mins
  • 6,478
  • 12
  • 56
  • 75

3 Answers3

0
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.
        }       
    }   
}
Brian Driscoll
  • 19,373
  • 3
  • 46
  • 65
0
try {
    Object data;
    // Processing
    if (data == null) {
        throw new NullPointerException();
    }
} catch (Exception exception) {
    // Unique code
}
spongebob
  • 8,370
  • 15
  • 50
  • 83
0
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;
        }
    }   
}
Jocke
  • 414
  • 3
  • 6
  • Thanks, in my case I don't want to enclose code 3 and 5 in the try block because I don't want any other exception to trigger the code in the catch catch clause for try { code 1 }. In addition code 2 and 4 must be executed if r != null too. – mins Aug 19 '14 at 18:43