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
答案 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程序员。