在java中返回try-catch的finally块。这个例子有什么好处吗? [英] return in try-catch's finally block in java. Is there any good point in this example?

查看:127
本文介绍了在java中返回try-catch的finally块。这个例子有什么好处吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对java并不熟悉,而且我最近看到一些同事写的一些令我困惑的代码。以下是它的要点:

I'm not familiar with java and I've been recently looking at some code written by some colleagues that's baffling me. Here's the gist of it:

public response newStuff(//random data inside) {
    try {
       response or = //gives it a value
       log.info(or.toString());
       return or;
    }
    catch ( Exception e) {
        e.printStackTrace();
    }
    finally {
        return null;
    }
}

这里添加finally块真的有任何意义吗?我不能只在catch块中添加返回null,它会执行相同的行为,或者我错了吗?

Is there really any point in adding a finally block here? Couldn't I just add the return null inside the catch block, which would execute the same behavior, or am I wrong?

推荐答案


在这里添加finally块真的有什么意义吗?

Is there really any point in adding a finally block here?

答案是响亮的no:在 finally 块中放置 return 语句是一个非常糟糕的主意。

The answer to this is a resounding "no": putting a return statement in the finally block is a very bad idea.


我只是在catch块中添加返回null,这会执行相同的行为,或者我错了?

I just add the return null inside the catch block, which would execute the same behavior, or am I wrong?

它与原始行为不符,但这是一件好事,因为它会修复它。而不是像原始代码那样无条件地返回 null ,而中的代码返回 catch block仅在出错时返回 null 。换句话说,除非有异常,否则 try 分支中返回的值将返回给调用者。

It wouldn't match the original behavior, but that's a good thing, because it would fix it. Rather than returning null unconditionally the way the original code does, the code with the return inside the catch block would return null only on errors. In other words, the value returned in the try branch would be returned to the caller unless there is an exception.

此外,如果你在 catch 块之后添加返回null ,你会看到在异常时返回 null 的正确效果。我会更进一步,在方法中放一个返回,如下所示:

Moreover, if you add return null after the catch block, you would see the correct effect of returning null on exception. I would go even further, and put a single return in the method, like this:

response or = null;
try {
   or = //gives it a value
   log.info(or.toString());
} catch ( Exception e) {
    e.printStackTrace();
}
return or;

这篇关于在java中返回try-catch的finally块。这个例子有什么好处吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆