【发布时间】: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