我正在开发一个应用程序,它将移动一些文件并更新数据库中的一些输入。如果找不到文件,将引发我自己的异常。但在那次异常之后,应用程序中断并停止移动文件。如何更改代码以使应用程序在发生异常后继续运行。 它应该打印出文件不存在,然后继续移动下一个文件。 这是我的代码:
import java.sql.;
import java.nio.file.; import java.io.*;
public class SortMainNewFinal { public static void main(String[] args) throws IOException, FileNotSynchronizedException {
//some not relevant code //...
//the relevant code
if(path.contains(timestamp)) {
if(filecheck(path,filename)) {
data.writeToFile("The File " + filename + " is already in its subordinated folder.");
}
}else {
checkDir(path+timestamp,filename);
filemove(path,timestamp,filename);
data.writeToFile("File "+filename+" has been moved into " + path + timestamp + "/" +
filename);
String strUpdate = ("update cm_documents set document_path=\""+path+timestamp+"/"
+filename + "\" where document_name=\""+filename+"\"");
data.writeToFile("SQL Statement is: " + strUpdate);
update.executeUpdate(strUpdate);
}
//Catch SQLException
}
private static void filemove(String path, String timestamp, String filename) throws IOException, FileNotSynchronizedException{ try { Files.move(Paths.get(path+filename), Paths.get(path+timestamp+"/"+filename)); }catch(NoSuchFileException e) { String error= "ERROR: The file " + filename + " has been moved, renamed or deleted and these changes are not synchronized with the database.";
String file_name="C:/database/logfile.log";
WriteFile data = new WriteFile(file_name,true);
data.writeToFile(error);
throw new FileNotSynchronizedException(filename);
}
} } class FileNotSynchronizedException extends Exception{
FileNotSynchronizedException(String filename) throws IOException{ super("The file" + filename + "has been moved, renamed or deleted and these changes are not synchronized with the database.");
} } 我的问题是,现在应用程序抛出了我的异常,然后中断,但我希望应用程序打印出异常,然后它将继续在我的应用程序顶部使用if语句等。
从主方法中删除throws ioexception、filenotsynchronizedeexception,因为您希望在那里处理异常而不是抛出它。如果保留catch块为空,则不会停止程序执行: try { filemove(path,timestamp,filename); }catch ( Exception e){ System.out.println("Some exception occurred -> "+e.getMessage()); }
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。