简体   繁体   English

为什么我的Java try…catch出现错误?

[英]Why am I getting errors with my Java try…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 . 我将开始自学更多有关Java错误处理的知识,这是我的第一个程序,其中我尝试查看特定的错误,而不是使用catch (Exception e)作为通用的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());
    }
}

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. 运行该命令时,我收到警告: This this is an unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body. This this is an unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body.

However, when I run with THIS catch block, 但是,当我使用此catch块运行时,

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() does not throw FileNotFoundException, even if the file does not exist. 即使文件不存在, File.delete()也不会引发FileNotFoundException。

FileNotFoundException is a checked exception (ie, not a RuntimeException), so any code that throws it must declare it. FileNotFoundException是一个已检查的异常(即,不是RuntimeException),因此任何引发该异常的代码都必须对其进行声明。 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. 因为File.delete()没有声明它抛出FileNotFoundException,所以编译器保证不会抛出该异常,并可以保证不会调用catch块。

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. 第二个包罗万象的块不会生成警告,因为它还会捕获RuntimeExceptions(RuntimeException扩展了Exception),编译器不会为您检查。 Thus, it might be invoked, the compiler isn't sure, so it doesn't warn you. 因此,可能会调用它,编译器不确定,因此不会警告您。

Java supports two kinds of exceptions: checked exceptions (statically checked) and unchecked exceptions ( RuntimeException and its subtypes). Java支持两种异常:受检查的异常(静态检查)和未经检查的异常( RuntimeException及其子类型)。

The Java compiler can tell at compile time whether a checked exception (such as FileNotFoundException ) can be thrown or can definitely not be thrown. Java编译器可以在编译时告知是否可以抛出已检查的异常(例如FileNotFoundException )。 It can't tell that for unchecked exceptions (such as IndexOutOfBoundsException ). 对于未经检查的异常(例如IndexOutOfBoundsException ),它无法分辨。 So it will warn about attempts to catch checked exceptions that cannot arise. 因此,它将警告尝试捕获不会出现的已检查异常。

If you catch Exception , it will never complain, because RuntimeException is a subtype of Exception , so your attempt will also try to catch exceptions such as IndexOutOfBoundsException . 如果捕获到Exception ,它将永远不会抱怨,因为RuntimeExceptionException的子类型,因此您的尝试还将尝试捕获诸如IndexOutOfBoundsException异常。

As others have noted, FileNotFoundException is never thrown by delete . 正如其他人指出的那样, delete绝不会抛出FileNotFoundException Furthermore it is a checked exception. 此外,这是一个检查的异常。 So the Java compiler will complain. 因此Java编译器会抱怨。

Because the type of error thrown doesn't match the one you're catching. 因为引发的错误类型与您正在捕获的错误类型不匹配。 Try this... 尝试这个...

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

That will show you the type of error you should be catching. 这将显示您应该捕获的错误类型。 Obviously this isn't good practice but it's a good exercise for seeing what's happening. 显然,这不是一个好习惯,但它是查看正在发生的事情的很好的练习。 Other answers on this page concerning checked and unchecked exceptions are pretty concise. 本页上有关已检查和未检查的异常的其他答案非常简洁。

If you look at the manual here delete() only throws a SecurityException. 如果您在此处查看手册,则 delete()仅引发SecurityException.

Also, it returns a boolean value which indicates whether or not the file was deleted. 同样,它返回一个boolean值,该boolean值指示是否删除了文件。 This should be all the information needed to indicate to the user if everything worked out. 这应该是向用户表明是否一切顺利的所有信息。

Isnt the message clear? 信息不清晰吗? As you dont construct a File object, a FileNotFoundException can never be thrown in this try block. 当您不构造File对象时,永远不会在此try块中引发FileNotFoundException Therefor the compilers informs you that the catch block in unneccessary. 因此,编译器会通知您不必要的catch块。

Look for IOException. 寻找IOException。 or deleteifExist method if you are not interested in the exception, if you want to retrn something, then file.exists() will help you fgure if the file is there or not. 或deleteifExist方法(如果您对异常不感兴趣),如果要撤消某些操作,则file.exists()将帮助您确定该文件是否存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 [Java]为什么在我的测试人员课程中遇到这些错误? - [Java]Why am I getting these errors in my tester class? 为什么使用try catch时会出现错误 - Why i am getting Error if i use try catch 我收到此代码的各种错误。 我是把 try/catch 放在正确的地方还是我的代码完全搞砸了? - I am getting all sorts of errors with this code. am I putting the try/catch in the correct place or is my code just completely messed up? 当我尝试在 Java 中运行我的套接字程序时,为什么会出现错误? - Why am I getting an error when I try to run my socket program in Java? 为什么在服务器/客户端聊天室程序中出现这些错误? - Why am I getting these errors in my Server/Client Chatroom program? 为什么我在android studio中的代码中出现错误? - Why am i getting errors in my code in android studio? 为什么我收到 java.lang.AbstractMethodError 错误? - Why I am getting java.lang.AbstractMethodError errors? 为什么我的 try catch 不能在 java 中找到工作? - Why my try catch does not catch job in java? 我的try-catch代码块做错什么了吗? - Am I doing something wrong with my try-catch block? 为什么我的 try catch 方法没有显示我为输入的字符串而不是 integer 编写的错误消息? (爪哇) - Why is my try catch method not showing the error message I wrote for an entered String instead of integer? (Java)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM