Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

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?

like image 680
dwwilson66 Avatar asked May 11 '26 03:05

dwwilson66


1 Answers

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

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.

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.

like image 105
Alex North Avatar answered May 12 '26 17:05

Alex North



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!