从方法,"try"块或"catch"块后返回?

Ebr*_*Him 21 java exception try-catch

以下两种方法有什么区别吗?

哪一个更好,为什么?

PRG1:

public static boolean test() throws Exception {
    try {
        doSomething();
        return true;
    } catch (Exception e) {
        throw new Exception("No!");
    }    
}
Run Code Online (Sandbox Code Playgroud)

PRG 2​​:

public static boolean test() throws Exception {
    try {
        doSomething();
    } catch (Exception e) {
        throw new Exception("No!");
    }
    return true;    
}
Run Code Online (Sandbox Code Playgroud)

Jor*_*nee 24

考虑这些您没有返回常量表达式的情况:

情况1:

public static Val test() throws Exception {
    try {
        return doSomething();
    } catch (Exception e) {
        throw new Exception("No!");
    }
    // Unreachable code goes here
}
Run Code Online (Sandbox Code Playgroud)

案例2:

public static Val test() throws Exception {
    Val toReturn = null;
    try {             
        toReturn = doSomething();
    } catch (Exception e) {
        throw new Exception("No!");
    }
    return toReturn;
}
Run Code Online (Sandbox Code Playgroud)

我更喜欢第一个.第二个更冗长,在调试时可能会引起一些混乱.

如果test()错误地返回null,并且您看到toReturn被初始化为null,您可能会认为问题存在test()(特别是当test()这不仅仅是一个简单的例子).

即使它只能返回null如果doSomething回报null.但这可能很难一目了然.


然后你可以争辩说,为了保持一致性,总是使用第一种形式更好.