引发异常后,如何催促应用程序继续运行?

时间:2019-10-14 06:47:01

标签: java mysql sql

我正在开发一个应移动一些文件并更新数据库中某些输入的应用程序。如果找不到该文件,则会抛出我自己的异常。但是在该异常之后,应用程序会中断并停止移动文件。我该如何更改代码,以便我的应用程序可以在异常发生后继续运行。

它将只打印出该文件不存在,然后继续移动下一个文件。

这是我的代码:

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语句等继续在应用程序顶部运行。

我想说我不是英语的母语,所以请原谅任何错误,我对编码很陌生,所以请原谅我的代码中的任何错误。 (:

1 个答案:

答案 0 :(得分:1)

从主方法中删除抛出IOException和FileNotSynchronizedException异常,因为您要在此处处理异常而不抛出异常。如果您将catch块留空,则它不会停止程序执行:

    try {
        filemove(path,timestamp,filename);
    }catch ( Exception e){
        System.out.println("Some exception occurred ->  "+e.getMessage());
    }