以下两种方法有区别吗?
哪个更好,为什么?
Prg1:
public static boolean test() throws Exception {
try {
doSomething();
return true;
} catch (Exception e) {
throw new Exception("No!");
}
}
Prg2:
public static boolean test() throws Exception {
try {
doSomething();
} catch (Exception e) {
throw new Exception("No!");
}
return true;
}
最佳答案
考虑这些不返回常量表达式的情况:
案例一:
public static Val test() throws Exception {
try {
return doSomething();
} catch (Exception e) {
throw new Exception("No!");
}
// Unreachable code goes here
}
案例 2:
public static Val test() throws Exception {
Val toReturn = null;
try {
toReturn = doSomething();
} catch (Exception e) {
throw new Exception("No!");
}
return toReturn;
}
我更喜欢第一个。第二个更冗长,在调试时可能会引起一些困惑。
如果 test()
错误地返回 null
,并且您看到 toReturn
被初始化为 null
,您可能认为问题出在 test()
中(尤其是当 test()
不仅仅是这样的简单示例时)。
即使它只能返回 null
如果 doSomething
返回 null
。但这可能一目了然。
然后您可以争辩说,为了保持一致性,最好始终使用第一种形式。
关于java - 从方法返回,在 "try" block 中还是在 "catch" block 之后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36965553/