This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
Granted, sometimes a preventable exception is still a checked exception (CloneNotSupportedException being the most annoying one), and I'm still wondering why FileNotFoundException exists*, but in most cases the rule is: if it can be prevented by adding checks it should be a RuntimeException, otherwise it should be a checked exception.
* there are two occurrences when a FileNotFoundException can be thrown:
- a file does not exist. But of course File.exists() can be used as a check.
- a file exists but cannot be opened as requested (e.g. trying to write to a read-only file). This could (should?) be handled with a regular IOException.
True, but that's beside the point. The point is, that I don't like the way the exception is used. Half of its purpose can be prevented, and for the other half the exception name is simply misleading. If I try to write to a read-only file I don't want a FileNotFoundException - I want a CannotWriteToFileException or something like that. Perhaps FileInaccessibleException.
Rajiv : The Java designers decided long ago that the compiler should be
used to enforce additional rules for some, but not all exceptions. Since
exceptions must be throwable, all exception types extend Throwable:
Throwable.Error(*) Throwable.Exception. And at the next level of the
exceptionheirarchy comes Throwable.Exception.Runtime(*).
The compiler does not enforce its "extra" rules for any exception of
the two types marked (*). All others, notably any extension of type
Exception, are examined more closely by the compiler. They are the
"checked" exceptions - as in "checked by the compiler".
Remember that it is just the two types, and their extensions, that are
the "unchecked" excpetions. If you throw a "new Throwable()" object,
for example, you will see the compiler do its extra checking.