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 the general exception types makes code hard to understand and maintain, and defeats much of the advantage of the Java exception-handling mechanism.
...
Code Block | ||
---|---|---|
| ||
try { doSomething(); } catch (Throwable e) { String msg = e.getMessage(); switch (msg) { case "stackfile not underflowfound": // Handle error break; case "connection timeout": // Handle error break; case "security violation": // Handle error break; default: throw e; } } |
If doSomething()
throws an exception or error whose type is a subclass of Exception
with the message "stack underflowof 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 will be is taken in the exception handlerhandling code.
However, any change to the exception message literals involved will break the code. For example, if a maintainer were to edit the throw expression to read throw new Exception("Stack Underflowfile not found");
, the exception would be rethrown by the code of the noncompliant code example rather than handled. Finally, exceptions may be thrown without a message.
This noncompliant code example falls under ERR08-EX0 of rule ERR08-J. Do not catch NullPointerException or any of its ancestors.
Compliant Solution
It is better to use existing specific exception types or to define This compliant solution uses specific exception types and defines new special-purpose exception types :where required.
Code Block | ||
---|---|---|
| ||
public class StackUnderflowExceptionTimeoutException extends Exception { StackUnderflowExceptionTimeoutException () { super(); } StackUnderflowExceptionTimeoutException (String msg) { super(msg); } } // ... try { doSomething(); } catch (StackUnderflowExceptionFileNotFoundException suee) { // Handle error } catch (TimeoutException te) { // Handle error } catch (SecurityException se) { // Handle error } |
...