【发布时间】:2013-12-12 05:18:35
【问题描述】:
我开始自学更多关于 Java 错误处理的知识,这是我第一个尝试查看特定错误的程序,而不是使用 catch (Exception e) 作为通用的包罗万象的 catch。
我正在删除一个文件并返回一条消息,说明该文件已成功删除或删除失败。在删除失败的情况下,如果找不到文件,我想发送错误消息。
这是我目前所处的位置:
public static void deleteOldConcatFiles(File concatFile) {
try
{
if(concatFile.delete()) {
System.out.println(concatFile.getName() + " is deleted!");
} else {
System.out.println("Delete operation failed.");
}
}
//
catch(FileNotFoundException f) {
System.out.println("Exception: "+ f.getMessage().getClass().getName());
}
}
当我运行它时,我收到一条警告:This this is an unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body.
但是,当我使用这个 catch 块运行时,
catch(Exception f) {
System.out.println("Exception: "+e.getMessage().getClass().getName());
}
我没有收到任何错误或警告消息。
为什么会发生这种情况,我可以做些什么来解决它?
【问题讨论】:
-
这似乎很容易解释。它不会抛出那个异常。也许你正在寻找
IOException -
Exception是RuntimeException的基类,但也有不是RuntimeException的异常,例如FileNotFoundException。RuntimeExceptions 不需要被捕获,也不需要throw子句,因此编译器无法判断它是否会被抛出。因此,它允许捕捉它们。
标签: java exception error-handling