Java“空白最终字段可能未被初始化”在方法奇怪中抛出异常 [英] Java "blank final field may not have been initialized" Exception thrown in method oddness

查看:398
本文介绍了Java“空白最终字段可能未被初始化”在方法奇怪中抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码:

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!


  1. 编译器不会看到 throws Exception 可以 c>在程序中停止编译时出现的错误是什么? / li>
  1. Doesn't the compiler see the throws Exception on the method called?
  2. How come an error which has the word may in it stops compilation?!?


推荐答案


  1. throwErrorMethod 永远不会正常完成。在规范中没有什么可以建议它应该。很遗憾,没有办法表示方法永远不会正常返回。

  1. 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屋!

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