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

后端 未结 6 1326
粉色の甜心
粉色の甜心 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:47

    Java supports two kinds of exceptions: checked exceptions (statically checked) and unchecked exceptions (RuntimeException and its subtypes).

    The Java compiler can tell at compile time whether a checked exception (such as FileNotFoundException) can be thrown or can definitely not be thrown. It can't tell that for unchecked exceptions (such as 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.

    As others have noted, FileNotFoundException is never thrown by delete. Furthermore it is a checked exception. So the Java compiler will complain.

提交回复
热议问题