Java“空白最终字段可能未被初始化”在方法奇怪中抛出异常 [英] Java "blank final field may not have been initialized" Exception thrown in method oddness
问题描述
我有一些代码:
final int var1;
if ( isSomethingTrue ) {
var1 = 123;
} else {
throwErrorMethod();
}
int var2 = var1;
而throwErrorMethod则定义为:
And throwErrorMethod is defined something like:
private void throwErrorMethod() throws Exception{
throw new Exception();
}
字段可能未被初始化编译错误为 var2 = var1
语句。如果我内联了方法,编译就好了!
And I get a blank final field may not have been initialized
compile error for the var2 = var1
statement. If I inline the method, compilation is fine!
- 编译器不会看到
throws Exception $
可以 c>在程序中停止编译时出现的错误是什么? / li>
- Doesn't the compiler see the
throws Exception
on the method called? - How come an error which has the word
may
in it stops compilation?!?
推荐答案
-
throwErrorMethod
永远不会正常完成。在规范中没有什么可以建议它应该。很遗憾,没有办法表示方法永远不会正常返回。
No, the compiler doesn't determine that the
throwErrorMethod
will never complete normally. There's nothing in the specification to suggest it should. Unfortunately there's no way to indicate that a method will never return normally.
这只是可能,因为有一个潜在的执行路径, 。这种执行路径的存在定义为错误。
It's only "may" because there's a potential execution path which doesn't initialize the variable. The presence of such an execution path is defined to be an error.
您可能会发现这对博客帖子第1部分; 第2部分)由Eric Lippert有趣。它是关于C#而不是Java,但它是相同的原则。
You may find this pair of blog posts (part 1; part 2) by Eric Lippert interesting. It's about C# rather than Java, but it's the same principle.
这篇关于Java“空白最终字段可能未被初始化”在方法奇怪中抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!