编译器说“变量可能没有被初始化”,尽管我有一个标志变量来保证它 [英] Compiler says "Variable might not have been initialized", although I have a flag variable to guarantee it

查看:206
本文介绍了编译器说“变量可能没有被初始化”,尽管我有一个标志变量来保证它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码片段:

Someclass someObject;
boolean success = true;
try {
    someObject = someOperation();
} catch (Exception e) {
    success = false;
}
if (success) {
    int number = Integer.valueOf(someObject.someMethord());
}

并且在行内:

 int number = Integer.valueOf(someObject.someMethord());

Java编译器抛出错误说

the Java compiler throws and error saying


错误:变量some​​Object可能尚未初始化。

Error: variable someObject might not have been initialized`.

但是,如果成功等于 true ,那么 someObject 将无法初始化,为什么我会收到此错误?

However, if success equals true, then there is no way someObject will not have been initialized, why am I getting this error?

推荐答案

编译器不会分析 success 标志与 someObject的初始化之间的关系变量。

The compiler doesn't analyze the relation between your success flag and the initialization of the someObject variable.

就编译器而言, someObject 可能无法初始化如果发生异常

As far as the compiler is concerned, someObject may not be initialized if an exception occurs.

您可以通过在catch块中将变量设置为 null 来解决该问题(而不是检查 success 变量,检查 someObject!= null )。

You can solve that issue by setting the variable to null in your catch block (and instead of checking your success variable, check that someObject != null).

或者您可以在try块中移动 int number = Integer.valueOf(someObject.someMethord()); 语句。

Or you can move the int number = Integer.valueOf(someObject.someMethord()); statement inside your try block.

这篇关于编译器说“变量可能没有被初始化”,尽管我有一个标志变量来保证它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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