Because an exception is caught by its type, it is better to define exceptions for specific purposes than to use the general exception types for multiple purposes. Throwing general exception types makes code hard to understand and maintain and defeats much of the advantage of the Java exception-handling mechanism.
Noncompliant Code Example
This noncompliant code example attempts to distinguish between different exceptional behaviors by looking at the exception's message:
doSomething() throws an exception or error whose type is a subclass of
Throwable, the switch statement allows selection of a specific case to execute. For example, if the exception message is "file not found," the appropriate action is taken in the exception-handling code.
However, any change to the exception message literals involved will break the code. For example, suppose this code is executed:
This exception should be handled by the first case clause, but it will be rethrown because the string does not match any case clause.
Furthermore, exceptions may be thrown without a message.
This noncompliant code example falls under ERR08-J-EX0 of ERR08-J. Do not catch NullPointerException or any of its ancestors because it catches general exceptions but rethrows them.
This compliant solution uses specific exception types and defines new special-purpose exception types where required.
Exceptions are used to handle exceptional conditions. If an exception is not caught, the thread will be terminated, which may cause the program to exit. An exception that is incorrectly caught or is caught at the wrong level of recovery will often cause incorrect behavior.