saveFile
抛出一个IOException
,你需要处理它或将它传递给调用者。
看看The try
Block更多细节
如果没有更多的背景下,很难说你应该做的。你可以处理异常的当前方法中...
else if(option == 5){
try {
SaveFile();
} catch (IOException exp) {
// Handle the exception, tell the user, roll back, what ever
// At the very least use exp.printStackTrace()
}
}
或声明当前方法抛出IOException
像SaveFile
方法确实
你SaveFile
方法也是潜在的,留下的文件打开。 ..
如果文件写作过程中由于某种原因失败,toTextFile.close
可能永远不会被调用,相反,你应该利用try-finally
块,例如
public static void SaveFile() throws IOException{
System.out.println("Saving File!");
FileWriter toTextFile = null;
try {
toTextFile = new FileWriter("output.txt");
for(x=0;x<new_num_book;x++){
toTextFile.write(name[x]);
}
} finally {
try {
toTextFile.close();
} catch (Exception exp) {
}
}
}
,或者如果您使用的是Java 7+,您可以利用的try-with-resources功能,例如...
public static void SaveFile() throws IOException{
System.out.println("Saving File!");
try (FileWriter toTextFile = new FileWriter("output.txt")) {
for(x=0;x<new_num_book;x++){
toTextFile.write(name[x]);
}
}
}
您可能还需要有Lesson: Exceptions和Code Conventions for the Java TM Programming Language,读这将使人们更容易阅读你的代码并让你阅读其他人
看起来你没有捕捉到'SaveFile'方法声明的IOException。但是我们需要检查更多的代码以确保这一点。 – 2014-10-10 02:42:35