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?
RuntimeException is used for errors when your application can not recover. For example, NullPointerException and ArrayOutOfBoundsException. You can avoid a RuntimeException with an 'if' command. You should not handle or catch it.
Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don't want to be bothered with specifying the exceptions your methods can throw.
Some people argue that all exceptions should extend from RuntimeException , but if you want to force the user to handle the exception, you should extend Exception instead.
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:
These are 2 significant scenarios that immediately come to my mind but there would be other scenarios of-course.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With