问题描述
这是我的代码片段:
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
但是,如果成功
等于 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.
这篇关于编译器说“变量可能没有被初始化”,尽管我有一个标志变量来保证它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!