0

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

编译错误是:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
oneRestore cannot be resolved
twoRestore cannot be resolved
threeRestore cannot be resolved
4

2 回答 2

8

范围始终是封闭的{}。您需要在try.

于 2013-06-03T03:21:50.837 回答
2

范围在try块内。在这种情况下,您需要在try块之前声明变量并使用标志来验证变量在访问之前是否已设置,如下所示:

gameCharacter oneRestore=null;
gameCharacter twoRestore=null;
gameCharacter threeRestore=null;
boolean wasRead = true;

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

if (wasRead) {
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());
}

顺便说一句,建议以大写开头的类名,因此gameCharacter->GameCharacter看起来更适合 Java 程序员。

于 2013-06-03T03:29:53.603 回答