Java:try/catch中的引用范围是什么?

she*_*lbc 0 java scope try-catch

try/catch的范围是什么?本质上我是反序列化一些对象并创建新的引用来存储它们.一旦它们被加载,我试图在引用中使用一个方法但是给出了下面的编译错误.

        try{
        ObjectInputStream is = new ObjectInputStream(new FileInputStream("saveGame.ser"));
        gameCharacter oneRestore = (gameCharacter) is.readObject();
        gameCharacter twoRestore = (gameCharacter) is.readObject();
        gameCharacter threeRestore = (gameCharacter) is.readObject();
    } catch (Exception ex) {ex.printStackTrace();}

    System.out.println("One's type is: " + oneRestore.getType());
    System.out.println("Two's type is: " + twoRestore.getType());
    System.out.println("Three's type is: " + threeRestore.getType());
Run Code Online (Sandbox Code Playgroud)

编译错误是:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
oneRestore cannot be resolved
twoRestore cannot be resolved
threeRestore cannot be resolved
Run Code Online (Sandbox Code Playgroud)

Joh*_*136 8

范围始终是封闭的{}.你需要在之前声明的变量try.

  • +1,但我强调它需要在`try`之前声明*并初始化*,因为Java不会让你读取一个可能尚未初始化的局部变量,即使它在范围内. (5认同)