为什么我的Java try ... catch出现错误? [英] Why am I getting errors with my Java try...catch?

查看:119
本文介绍了为什么我的Java try ... catch出现错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始自学更多有关Java错误处理的知识,这是我的第一个程序,其中我尝试查看特定的错误,而不是使用 catch(异常e)作为通用的 catch

I'm starting to teach myself more about Java error handling, and this is my first program where I'm trying to see specific errors instead of using catch (Exception e) as a generic catch-all catch.

我要删除文件并返回一条消息,指出文件已成功删除或删除失败。在删除失败的情况下,如果找不到该文件,我想传递一条错误消息。

I'm deleting a file and returning a message that the file was deleted successfully or that the deletion was a failure. In cases where the deletion fails, I want to deliver an error message if the file is not found.

到目前为止,我在这里:

Here's where I am so far:

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());
    }
}

当我运行该命令时,我会收到警告:这是FileNotFoundException的无法访问的catch块。不会从try语句主体中引发该异常。

When I run that, I'm getting a warning: This this is an unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body.

但是,当我运行此catch块时,

However, when I run with THIS catch block,

catch(Exception f) {
     System.out.println("Exception: "+e.getMessage().getClass().getName());
}

我没有收到错误或警告消息。

I get no error or warning message.

为什么会发生这种情况,我该怎么解决?

Why is this happening, and what can I do to fix it?

推荐答案

File.delete()不会抛出FileNotFoundException,即使该文件不存在。

File.delete() does not throw FileNotFoundException, even if the file does not exist.

FileNotFoundException是一个已检查的异常(即,不是RuntimeException),因此任何引发该异常的代码都必须对其进行声明。因为 File.delete()没有声明它抛出FileNotFoundException,所以编译器保证不会抛出该异常,并且可以保证您的catch块将永远不会被调用。

FileNotFoundException is a checked exception (i.e., not a RuntimeException), so any code that throws it must declare it. Because File.delete() does not declare that it throws FileNotFoundException, the compiler guarantees that it won't, and can promise that your catch block will never be invoked.

第二个包罗万象的块不会生成警告,因为它还会捕获RuntimeExceptions(RuntimeException扩展了Exception),编译器不会为您检查。因此,可能会调用它,编译器不确定,因此不会警告您。

The second, catch-all block does not generate a warning because it also catches RuntimeExceptions (RuntimeException extends Exception), which the compiler does not check for you. Thus, it might be invoked, the compiler isn't sure, so it doesn't warn you.

这篇关于为什么我的Java try ... catch出现错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆