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

时间:2013-06-03 03:19:52

标签: 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());

编译错误是:

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

2 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分: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程序员。