0

是否可以通过不使用标签(并且不重复太多代码或创建太多方法)来改进此 Java 代码?

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

编辑:

我使用break/犯了一个错误label。我将它们用作goto(code after lab1must be executed also if r!=null。这不是它们的目的,并且此类代码无法编译,因为 break 无法向前引用标签。我知道goto在 Java 中没有等效的(可以在任何地方分支的语句) .

Exception1我使用强制if退出外部的自定义编写了代码:

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;

这不会是代码时尚竞赛的赢家,但至少它有效。感谢您的回答和评论。

4

3 回答 3

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;
        }
    }   
}
于 2014-08-19T18:29:32.937 回答
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.
        }       
    }   
}
于 2014-08-19T18:21:21.063 回答
0
try {
    Object data;
    // Processing
    if (data == null) {
        throw new NullPointerException();
    }
} catch (Exception exception) {
    // Unique code
}
于 2014-08-19T18:25:22.290 回答