我已经编写了自己的异常,但我无法抛出它。
应用程序仍然终止并给出标准错误消息:
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 不存在。然后它会打印出:
The File has been renamed, moved or deleted and those changes are not synchronized with the 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");
}
}
我希望有人可以帮助我,并向我解释如何抛出自己的错误消息。显示错误消息后,应用程序应继续移动文件。
很抱歉,如果我在代码中犯了一些愚蠢的错误,我对这个主题还很陌生。英语不是我的母语,所以请原谅任何语法或拼写错误。 希望您度过愉快的一天。
最佳答案
方法Files.move(...)
抛出一个NoSuchFileException
,它来自包java.nio.file
。
您的 NoSuchFileException
实现可能具有相同的名称,但永远不会抛出它。因此,您必须捕获
java.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 子句即可。
关于java - 如何用Java中预先编写的方法抛出我自己的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58197013/