What is the reason behind ClassNotFoundException
being a checked exception?
I've been guessing and googling trying to understand why consider class not found as checked exception, because all my mind tells me that it should be unchecked.
Exceptions are usually checked when the receiver can/should take some meaningful action to correct the problem at runtime.
Unchecked Exceptions — The Controversy says:
Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
The most common source of ClassNotFoundException
s is code like
classLoader.loadClass(className);
that reflectively loads a class based on a name found in a configuration file, serialized input, or remote procedure call.
This is in contrast to ClassNotFoundError
which most often result from a program that was statically compiled with other classes which cannot be found by the JVM's linker at runtime.
What distinguishes the reflective use case (checked) from a failure to link statically compiled code (runtime error)?
Reflective: The caller knows where the string came from and why the load was attempted.
Static: Caller is just trying to use a class that was available at compile time. No context is available.
Reflective: Caller can fail-over to a different implementation or try a default strategy.
Static: The Java language does not explicitly support substituting different link points.
Reflective: Caller should often convert the error to a different kind, like
an IOException
on failure to deserialize.
Static: If part of your program is missing, then you can't rely on the necessary part of your program being there to explain why one part is missing to other parts.
A ClassNotFoundException
is thrown when your code calls Class.forName()
on a class name that cannot be resolved to a class on your application's classpath (loosely speaking). It could be a misspelled classname supplied by the application's user, and hence there is potentially a reason to report it to the user and maybe even retry with a corrected classname. In other words this could be a recoverable error ... in some circumstances ... so you could argue that the decision to make it checked is appropriate.
Either way:
By contrast, if you get a problem during the class loading / initialization process, you are likely to get a NoClassDefFoundError
. This is definitely not recoverable. When that happens you've got one or more classes in a state where they exist in the JVM but cannot be initialized or instantiated. (You will also see NoClassDefFoundError
if the JVM fails to find your nominated entrypoint class. But if that happens, your application won't even get a chance to try to recover ...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With