Why am I getting errors with my Java try…catch?

后端 未结 6 1385
粉色の甜心
粉色の甜心 2021-01-24 05:09

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)

6条回答
  •  既然无缘
    2021-01-24 05:49

    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.

提交回复
热议问题