是否可以通过不使用标签(并且不重复太多代码或创建太多方法)来改进此 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 lab1
must 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;
这不会是代码时尚竞赛的赢家,但至少它有效。感谢您的回答和评论。