局部变量可能未被初始化 - 在方法中检测未检查的异常throw [英] The local variable might not have been initialized - Detect unchecked exception throw within a method
本文介绍了局部变量可能未被初始化 - 在方法中检测未检查的异常throw的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些这样的代码:
public void method(){
Object o;
try {
o = new Object();
} catch(Exception e){
//处理,几行
throw new Error(); //我们自己的unchecked异常
}
doSomething(o);
}
我有很多方法在catch中有相同的代码块,所以我想提取它到一个方法,以便我可以保存一些行。我的问题是,如果我这样做,我得到一个编译器错误
局部变量o可能没有被初始化。
public void method(){
Object o;
try {
o = new Object();
} catch(Exception e){
handleError();
}
// doSomething(o);编译器错误
}
private void handleError()throws Error {
//处理几行
throw new Error();
}
是否有任何解决方法?
public void method(){
Object o = null;
try {
o = new Object();
} catch(Exception e){
handleError();
}
doSomething(o);
}
在使用未初始化的局部变量之前,不会得到编译失败
I have some code with this structure:
public void method() {
Object o;
try {
o = new Object();
} catch (Exception e) {
//Processing, several lines
throw new Error(); //Our own unchecked exception
}
doSomething(o);
}
I have quite a few methods in which I have the same code in the catch block, so I want to extract it to a method so that I can save some lines. My problem is, that if I do that, I get a compiler error " The local variable o might not have been initialized".
public void method() {
Object o;
try {
o = new Object();
} catch (Exception e) {
handleError();
}
//doSomething(o); compiler error
}
private void handleError() throws Error {
//Processing, several lines
throw new Error();
}
Is there any workaround?
解决方案
You need to initialize local variables before they are used as below
public void method() {
Object o=null;
try {
o = new Object();
} catch (Exception e) {
handleError();
}
doSomething(o);
}
You will not get the compilation failure until you use local variable which was not initialized
这篇关于局部变量可能未被初始化 - 在方法中检测未检查的异常throw的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文