Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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 a variety of multiple purposes. Throwing the general exception types makes code hard to understand and maintain and defeats much of the advantage of the Java exception-handling mechanism.

...

If doSomething throws an exception , whose type is a subclass of Exception, with  with the message "stack underflow," then the appropriate action will be taken in the exception handler. However, any change to the literals involved will break the code. For example, if a maintainer should were to edit the throw expression to read throw Exception("Stack Underflow");, the exception will would be rethrown by the code of the noncompliant code example rather than handled. Also, an exception exceptions may be thrown with no without a message.

Compliant Solution

It is better to user specific use existing exception specific exception types or to define new , special-purpose exception types:

...

Exceptions are used to handle exceptional conditions. If an exception is not caught, the program will be terminated. An exception that is incorrectly caught or is caught at the wrong level of recovery will likely often cause incorrect behavior.

...