局部变量可能尚未初始化 - 检测方法内未检查的异常抛出 [英] The local variable might not have been initialized - Detect unchecked exception throw within a method

查看:18
本文介绍了局部变量可能尚未初始化 - 检测方法内未检查的异常抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些具有这种结构的代码:

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);
}

我有很多方法在catch块中有相同的代码,所以我想把它提取到一个方法中,这样我就可以保存一些行.我的问题是,如果我这样做,我会收到编译器错误局部变量 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();
}

有什么解决办法吗?

推荐答案

局部变量使用前需要先初始化

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

这篇关于局部变量可能尚未初始化 - 检测方法内未检查的异常抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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