java - 从方法返回,在 "try" block 中还是在 "catch" block 之后?

标签 java exception try-catch

以下两种方法有区别吗?

哪个更好,为什么?

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/

相关文章:

java - 变量 'adapter' 是从内部类中访问的。需要宣布最终

Java Midi 播放器程序

java - 为什么我没有正确捕获这个异常?

java 。实例变量长度

java - 关于try-catch的问题

c++ - 异常处理。如何抛出一个迭代器?

JAVA + try catch(FileNotFoundException e) 进入 catch(Exception e)?

java - 正则表达式将文本分成 6 列

java - Spring Boot请求映射正则表达式

java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?