Exception

Checked vs Unchecked

Java defined checked & unchecked only from Compiler perspective. All RuntimeException & Error & its subclasses are unchecked.

When to use/define Checked-Exception and when unchecked exception?

Recoverable is the keyword. When the exception/error/problem is "recoverable", define recoverable. Recoverable here means that the issue can be based on "wrong" input which can be changed be called. Eg, processCheck can throw "recoverable" exception of "InsufficientFund" or "CheckIsStopPayment", as the client can send different check or post more funds. However, "DatabaseDown" is "not-recoverable" problem

An article defined(referece1) the recoverable (contingency) & non-recoverable (fault) as below:

Rules:

1. Do now throw the domain/layer specific exception to other layers. E.g. SQLExpception(CheckedException) should be caught by DAO. After that, if DAO think it is recoverable, it should throw another Checked Exception or if case it thinks it is not-recoverable, throw unchecked exception.

Extending this definition: Throw exceptions appropriate to the abstraction. That means, exceptions thrown by a method should be defined at an abstraction level consistent with what the method does, not necessarily with the low-level details of how it is implemented. For example, a method that loads resources from files, databases, or JNDI should throw some sort of ResourceNotFound exception when it cannot find a resource (generally using exception chaining to preserve the underlying cause), rather than the lower-level IOException, SQLException, or NamingException.

2. Avoid exception as flow

References:

  1. http://www.oracle.com/technetwork/articles/entarch/effective-exceptions2-097044.html

  2. http://stackoverflow.com/questions/27578/when-to-choose-checked-and-unchecked-exceptions?lq=1