java中finally子句中的return语句有危险吗?

Foo*_*Foo 5 java exception

看下面的代码。尽管 catch 子句本身会引发异常,但 finally 块的 return 语句会导致该异常被吞掉。即使 catch 块中出现问题,此方法也会返回 420。

private static int foo() throws Exception
{
    try {
        throw new Exception("try");

    } catch (Exception ex) {
        throw new Exception("catch");
    } finally {
        String s = "";
        return 420;
    }


}
Run Code Online (Sandbox Code Playgroud)

Mei*_*aft 1

如果遇到异常,您应该返回其他内容。仅当在最终返回语句中使用引发该异常的变量时,该异常才是危险的。考虑一下:

int a;
try{
 //...
}catch(Exception e){
 //a throws an exception somehow
}finally{
 returns a;
}
Run Code Online (Sandbox Code Playgroud)

当你a像这样在另一侧使用时:

a += 1;
Run Code Online (Sandbox Code Playgroud)

你会得到一个危险的异常

我的建议是这样做:

try{
 //...
}catch(Exception e){
 //a throws an exception somehow
 returns -1;
}finally{
 returns a;
}
Run Code Online (Sandbox Code Playgroud)

而在另一边:

if(return_value == -1) // skip or do something else;
Run Code Online (Sandbox Code Playgroud)

这样,您就不会在另一端遇到不可预测的异常。