本文介绍了Java try-finally返回设计问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,尝试{...}最终{...}对我来说有些不直观。如另一个问题所示,,如果你在try块中有一个return语句,如果定义了finally块,它将被忽略。例如,函数

  boolean test(){
try {
return true;
}
最后{
返回false;
}
}

将始终返回false。我的问题:这是为什么?这个由Java制定的设计决策背后有一个特定的哲学吗?感谢任何见解,谢谢。



编辑:我特别感兴趣的是'为什么'Java认为可以违反我定义的语义。如果我在try块中'返回',那么该方法应该在那里返回。但是JVM决定忽略我的指令并从实际上还没有 到达的子程序返回。

解决方案

从技术上讲,如果 finally 块为 return em>已定义,仅当finally块还包含 return



这是一个可疑的设计回想起来可能错误的决定(很像默认情况下引用是可空的/可变的,并且根据一些情况,检查异常)。在许多方面,这种行为与对最终的含义的口语理解完全一致 - 无论事先在中发生什么,请尝试阻止,始终运行此代码。因此,如果 finally 块返回true ,整体效果必须始终为true,不是吗? / p>

一般来说,这很少是一个很好的习惯用法,你应该使用 finally 块来清理/关闭资源但很少从它们那里返回一个值。


In Java, a try { ... } finally { ... } is executed somewhat unintuitively to me. As illustrated in another question, Does finally always execute in Java?, if you have a return statement in the try block, it will be ignored if a finally block is defined. For example, the function

boolean test () {
    try {
        return true;
    }
    finally {
        return false;
    }
}

will always return false. My question: why is this? Is there a particular philosophy behind this design decision made by Java? I appreciate any insight, thank you.

Edit: I'm particularly interested as to 'why' Java thinks it's ok to violate the semantics that I define. If I 'return' in a try block, the method should return right then and there. But the JVM decides to ignore my instruction and return from a subroutine that actually hasn't yet been reached.

解决方案

Technically speaking, the return in the try block won't be ignored if a finally block is defined, only if that finally block also includes a return.

It's a dubious design decision that was probably a mistake in retrospect (much like references being nullable/mutable by default, and, according to some, checked exceptions). In many ways this behaviour is exactly consistent with the colloquial understanding of what finally means - "no matter what happens beforehand in the try block, always run this code." Hence if you return true from a finally block, the overall effect must always to be to return true, no?

In general, this is seldom a good idiom, and you should use finally blocks liberally for cleaning up/closing resources but rarely if ever return a value from them.

这篇关于Java try-finally返回设计问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 18:38