当无法分配变量时,可能已经分配了变量 [英] variable might already have been assigned when it cannot be assigned

查看:329
本文介绍了当无法分配变量时,可能已经分配了变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

研究此代码:

public class TestFinalAndCatch {
    private final int i;

    TestFinalAndCatch(String[] args) {
        try {
            i = method1();
        } catch (IOException ex) {
            i = 0;  // error: variable i might already have been assigned
        }
    }

    static int method1() throws IOException {
        return 1;
    }
}

编译器说 java:变量我可能已被分配

但对我来说这看起来是不可能的情况。

But for me it is looks like impossible situation.

推荐答案

i 是最终的,因此只能分配一次。编译器可能不够聪明,无法实现如果抛出异常,则不会发生第一个赋值,如果不抛出异常,则不会发生第二个赋值。

i is final, so it can only be assigned once. The compiler is probably not smart enough to realize that if an exception is thrown, the first assignment won't take place, and if an exception isn't thrown, the second assignment won't take place.

这篇关于当无法分配变量时,可能已经分配了变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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