【问题标题】:How to throw my own Exception with a pre written method in Java?如何使用 Java 中预先编写的方法抛出我自己的异常?
【发布时间】:2019-10-02 07:31:49
【问题描述】:

我已经编写了自己的异常,但我不能抛出它。

应用程序仍然终止并给我标准错误消息:

Exception in thread "main" java.nio.file.NoSuchFileException: H:\db_sort\pdfs\test_5_database
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileCopy.move(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.move(Unknown Source)
at java.nio.file.Files.move(Unknown Source)
at ExceptionTest.filemove(ExceptionTest.java:22)
at ExceptionTest.main(ExceptionTest.java:9)

应用程序必须移动一些文件,但可能是应该移动的文件不存在。然后程序将打印出文件无法移动,然后程序将移动到下一个文件。

这是我想在其中抛出异常的一段代码。 文件 test_5_database 不存在。然后它会打印出来:

文件已被重命名、移动或删除,并且这些更改未与数据库同步。

这是我的代码(我不会发布我的整个代码,我只会发布我的异常问题):

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ExceptionTest {

  public static void main(String[] args) throws IOException {
      try {
          filemove();
        
          System.out.println("The file has been moved!");
      }
       catch(NoSuchFileException e) {
           System.out.println(e.getMessage());
           e.printStackTrace();
       }

    
 }

 private static void filemove() throws IOException, NoSuchFileException{
    Files.move(Paths.get("H:/db_sort/pdfs/test_5_database"),Paths.get("H:/db_sort/pdf s/2019-08/test_5_database"));
 }

}

class NoSuchFileException extends Exception{
    NoSuchFileException(){
        super("The file has been moved, renamed or deleted and those changes 
               are not synchronized with the database");
    }
}

我希望有人可以帮助我并解释我如何抛出自己的错误消息。显示错误消息后,应用程序应继续移动文件。

对不起,如果我在代码中犯了一些愚蠢的错误,我对这个话题很陌生。英语不是我的母语,所以请原谅任何语法或拼写错误。 我希望你有一个愉快的一天。

【问题讨论】:

  • 它被抛出。然后用e.printStackTrace()main 中打印堆栈跟踪。程序终止,因为您在捕获异常后什么都不做。如果你在 main 方法的末尾打印出一些东西,你会注意到它被打印出来了。
  • 它被抛出。它也被抓住了。但是你永远不应该期望从应用程序的入口点抛出异常,你将永远无法以体面的方式处理错误,从而导致应用程序不可避免的崩溃。
  • 您似乎还决定将异常命名为与引发的异常相同的名称。这真的是个好主意吗?阅读this
  • @Kayaman 但我没有收到消息文件已被移动、重命名或删除,并且这些更改未与数据库同步。” 程序刚刚终止我不希望程序终止,因为它会移动下一个文件。
  • @Stultuske 以及如何在我的代码中解决这个问题?我不希望应用程序崩溃。

标签: java exception error-handling


【解决方案1】:

方法Files.move(...) 抛出一个来自包java.nio.fileNoSuchFileException

NoSuchFileException 的实现可能具有相同的名称,但它永远不会被抛出。所以你必须catchjava.nio.file.NoSuchFileException 并抛出你自己的my.package.NoSuchFileException

但也许最好(避免所有混淆)将您的异常重命名为例如FileNotSynchronizedException。你可以这样做:

第一个选项(您可能希望删除 NoSuchFileException 的导入)

private static void filemove() throws IOException, NoSuchFileException{
     try{
        Files.move( Paths.get("H:/db_sort/pdfs/test_5_database"),Paths.get("H:/db_sort/pdf s/2019-08/test_5_database"));
     }catch(java.nio.file.NoSuchFileException e){
         throw new my.package.NoSuchFileException();
     }
}

第二个选项

private static void filemove() throws IOException, FileNotSynchronizedException{
     try{
        Files.move( Paths.get("H:/db_sort/pdfs/test_5_database"),Paths.get("H:/db_sort/pdf s/2019-08/test_5_database"));
     }catch(NoSuchFileException e){
         throw new my.package.FileNotSynchronizedException();
     }
}

看到方法头中不同的throws 子句了吗?您只需通过抛出自己的异常来更改异常。

恕我直言,第二个选项更好,您可以避免与java.nio.files 中的现有异常发生冲突,它使您有机会做出更具体的异常。例如,如果您想同时捕获 IOException 并抛出自己的异常,那么只需添加另一个 catch 子句。

【讨论】:

  • 我试过了,它可以工作,但我怎样才能重写我的程序,让它继续移动文件?例如:test_5_database 不存在。然后它打印出我的异常,现在正在工作。现在应用程序将转到下一个文件,例如 _test_6_database。该文件已存在,应再次移动。用同样的方法File.move(...)。我该怎么做?
  • 我猜这是一个不同的问题。在您的示例代码中,您没有将任何参数(如文件名)传递给您的 filemove() 方法。如果您将文件名作为参数传递到哪里呢:filemove(String filename) 然后遍历所有文件。在您调用filemove 方法的迭代/循环中,您放置捕获异常的try-catch 块,记录它们,然后继续循环。 for(String file: myFiles){ try{ filemove(file);}catch(MyExceptions e){Logger.getLogger.....}}
  • 嘿,我该怎么做呢?我写了一些东西,它没有给我任何错误,但它没有移动我的文件。这是我的代码:private static void filemove(String path,String timestamp,String filename) throws IOException, FileNotSynchronizedException{ File[] files =new File(path+timestamp).listFiles(); for(File file:files) { try{ Files.move(Paths.get(path+filename),Paths.get(path+timestamp+"/"+filename)); }catch(NoSuchFileException e) { throw new FileNotSynchronizedException(); } } }
  • 请针对这个新问题打开一个新问题,以便其他 SO 用户也可以帮助您。不要忘记粘贴filemove 方法的代码和调用该方法的代码。
  • 我已经解决了这个问题,但还是感谢您的帮助。
【解决方案2】:

如果您创建新异常,请为其命名与现有异常不同。

要抛出异常,你应该写:

throw new ExceptionName("message");

例如:

throw new UnsupportedOperationException();

如果要在文件不存在时抛出异常:

if(checkIfFileExists) {
    throw new ExceptionName("message");
}

在您执行操作之前。

在您的情况下,最好的方法是更改​​ catch (在这种情况下不需要创建新异常),例如:

   catch(NoSuchFileException e) {
       System.out.println("The file has been moved, renamed or deleted and those 
       changes are not synchronized with the database");
       System.out.println(e.getMessage());
       e.printStackTrace();
   }

【讨论】:

    【解决方案3】:
    You can throw a custom exception like below, hope my understanding is correct.
    
    package test;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    
    public class ExceptionTest {
    
      public static void main(String[] args) throws NoSuchFileException {
          try {
              filemove();
    
              System.out.println("The file has been moved!");
          }
           catch(IOException e) {
               throw new NoSuchFileException();
           }
    
    
     }
    
     private static void filemove() throws IOException{
            Files.move(Paths.get("H:/db_sort/pdfs/test_5_database"),Paths.get("H:/db_sort/pdf s/2019-08/test_5_database"));
     }
    
    }
    
    class NoSuchFileException extends Exception{
        NoSuchFileException(){
            super("The file has been moved, renamed or deleted and those changes are not synchronized with the database");
        }
    }
    
    Output : 
    Exception in thread "main" test.NoSuchFileException: The file has been moved, renamed or deleted and those changes are not synchronized with the database
        at test.ExceptionTest.main(ExceptionTest.java:15)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-17
      • 2013-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多