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

编译错误是:

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

作用域始终是封闭的{}。您需要在try之前声明变量。

作用域在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());
}

BTW,建议用大写字母开始一个类名,因此gameCharacter -> GameCharacter看起来更适合Java程序员。

最新更新