我试图随机获取真相,但没有成功,所以我转向你。如何处理 FileNotFoundException 异常(实际上是一般的任何异常),以便 try 仅扩展到对象的创建,同时我可以在 try 之外使用创建的对象。我想出的选项之一如下所示,但在 createOutDataForAdmin 和 createOutDataForAdmin 方法的参数中,据称 PrintStream 类的 outAdmin 和 outComputer 对象未初始化。
public class main {
public static void main(String args[]){
Scanner keyboard=new Scanner(System.in);
PrintStream outAdmin,outComputer;
Scanner scan;
try {
outAdmin = new PrintStream("Out data for admin.txt");
outComputer = new PrintStream("Out data for compute.txt");
scan = new Scanner(new File("Out data for admin.txt"));
}catch (FileNotFoundException exception){
System.out.println("File not found");
}
User arrayUsers[]=new User[1];
createOutDataForAdmin(arrayUsers,outAdmin);
createOutDataForComputer(arrayUsers,outComputer);
}
还有另一种选择。代码还是一样的,只是 try catch 块被改变了。尝试之外的所有相同问题我都无法使用创建的对象。
try {
PrintStream outAdmin = new PrintStream("Out data for admin.txt");
PrintStream outComputer = new PrintStream("Out data for compute.txt");
Scanner scan = new Scanner(new File("Out data for admin.txt"));
}catch (FileNotFoundException exception){
System.out.println("File not found");
}
第三个选项,我把所有的代码都塞进了try。我认为说明它没有意义。在我看来,它不应该看起来像这样,尽管在这种情况下一切都按应有的方式工作。如果我在术语上搞砸了,我很抱歉批评)