Possible Duplicate:
In Java, when should I create a checked exception, and when should it be a runtime exception?
When should I derive an exception from RuntimeException
instead of Exception
?
A RuntimeException
does not have to be declared in a method's throws
clause, which may be good since it doesn't have to specifically listed or bad because it is good practice to explicitly declare a method's exception.
Thoughts?
From Unchecked Exceptions -- The Controversy:
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.
Note that an unchecked exception is one derived from RuntimeException
and a checked exception is one derived from Exception
.
Why throw a RuntimeException
if a client cannot do anything to recover from the exception? The article explains:
Runtime exceptions represent problems
that are the result of a programming
problem, and as such, the API client
code cannot reasonably be expected to
recover from them or to handle them in
any way. Such problems include
arithmetic exceptions, such as
dividing by zero; pointer exceptions,
such as trying to access an object
through a null reference; and indexing
exceptions, such as attempting to
access an array element through an
index that is too large or too small.
There are many scenarios in enterprise application development where you would use RuntimeException instead of Exception, following are two such scenarios that are pretty common:
- While implementing Exception handling as an aspect (separating the concern design principle), in most modern day frameworks you would declarative handle exceptions and associate specific exception handling blocks rather than hardcoding the same. One good example of this is JDBC template in Spring that converts all the SQL exceptions to RuntimeException so developer doesnot write try catch blocks while writting data access logic. you can define exception handler declaratively that can provide different behavior in dev env. and different behavior in production. Similar implementation is there in Struts 1.x Action class also, where the execute method is declared to throw Exception and there is separate ExceptionHandler mapped in struts-config for handling specific exceptions. Though this is not example of RuntimeException but the design principle is same to separate the concern of normal execution and exception handling.
- Another use of RuntimeException is in EJB and other Transaction Managers where in the transactions are controller by container. In such containers by convention if you throw RuntimeException from within your code the transaction would rollback - the same would not happen if you throw Exception
These are 2 scenarios that immediately come to my mind there would be other scenarios of-course.