Difference between java.lang.RuntimeException and java.lang.Exception
Someone please explain the difference between java.lang.RuntimeException
and java.lang.Exception
? How do I decide which one to extend if I create my own exception?
Generally RuntimeExceptions are exceptions that can be prevented programmatically. E.g NullPointerException
, ArrayIndexOutOfBoundException
. If you check for null
before calling any method, NullPointerException
would never occur. Similarly ArrayIndexOutOfBoundException
would never occur if you check the index first. RuntimeException
are not checked by the compiler, so it is clean code.
EDIT : These days people favor RuntimeException
because the clean code it produces. It is totally a personal choice.
In Java, there are two types of exceptions: checked exceptions and un-checked exceptions. A checked exception must be handled explicitly by the code, whereas, an un-checked exception does not need to be explicitly handled.
For checked exceptions, you either have to put a try/catch block around the code that could potentially throw the exception, or add a "throws" clause to the method, to indicate that the method might throw this type of exception (which must be handled in the calling class or above).
Any exception that derives from "Exception" is a checked exception, whereas a class that derives from RuntimeException is un-checked. RuntimeExceptions do not need to be explicitly handled by the calling code.
Before looking at the difference between java.lang.RuntimeException
and java.lang.Exception
classes, you must know the Exception
hierarchy. Both Exception
and Error
classes are derived from class Throwable
(which derives from the class Object
). And the class RuntimeException
is derived from class Exception
.
All the exceptions are derived either from Exception
or RuntimeException
.
All the exceptions which derive from RuntimeException
are referred to as unchecked exceptions. And all the other exceptions are checked exceptions. A checked exception must be caught somewhere in your code, otherwise, it will not compile. That is why they are called checked exceptions. On the other hand, with unchecked exceptions, the calling method is under no obligation to handle or declare it.
Therefore all the exceptions which compiler forces you to handle are directly derived from java.lang.Exception
and all the other which compiler does not force you to handle are derived from java.lang.RuntimeException
.
Following are some of the direct known subclasses of RuntimeException.
AnnotationTypeMismatchException,
ArithmeticException,
ArrayStoreException,
BufferOverflowException,
BufferUnderflowException,
CannotRedoException,
CannotUndoException,
ClassCastException,
CMMException,
ConcurrentModificationException,
DataBindingException,
DOMException,
EmptyStackException,
EnumConstantNotPresentException,
EventException,
IllegalArgumentException,
IllegalMonitorStateException,
IllegalPathStateException,
IllegalStateException,
ImagingOpException,
IncompleteAnnotationException,
IndexOutOfBoundsException,
JMRuntimeException,
LSException,
MalformedParameterizedTypeException,
MirroredTypeException,
MirroredTypesException,
MissingResourceException,
NegativeArraySizeException,
NoSuchElementException,
NoSuchMechanismException,
NullPointerException,
ProfileDataException,
ProviderException,
RasterFormatException,
RejectedExecutionException,
SecurityException,
SystemException,
TypeConstraintException,
TypeNotPresentException,
UndeclaredThrowableException,
UnknownAnnotationValueException,
UnknownElementException,
UnknownTypeException,
UnmodifiableSetException,
UnsupportedOperationException,
WebServiceException
An Exception
is checked, and a RuntimeException
is unchecked.
Checked means that the compiler requires that you handle the exception in a catch, or declare your method as throwing it (or one of its superclasses).
Generally, throw a checked exception if the caller of the API is expected to handle the exception, and an unchecked exception if it is something the caller would not normally be able to handle, such as an error with one of the parameters, i.e. a programming mistake.
The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking, since the compiler cannot establish that run-time exceptions cannot occur. (from JLS).
In the classes that you design you should subclass Exception and throw instances of it to signal any exceptional scenarios. Doing so you will be explicitly signaling the clients of your class that usage of your class might throw exception and they have to take steps to handle those exceptional scenarios.
Below code snippets explain this point:
//Create your own exception class subclassing from Exception
class MyException extends Exception {
public MyException(final String message) {
super(message);
}
}
public class Process {
public void execute() {
throw new RuntimeException("Runtime");
}
public void process() throws MyException {
throw new MyException("Checked");
}
}
In the above class definition of class Process, the method execute
can
throw a RuntimeException but the method declaration need not specify that
it throws RuntimeException.
The method process
throws a checked exception and it should declare that it
will throw a checked exception of kind MyException and not doing so will be
a compile error.
The above class definition will affect the code that uses Process class as well.
The call new Process().execute()
is a valid invocation where as the call of form
new Process().process()
gives a compile error. This is because the client code should
take steps to handle MyException
(say call to process() can be enclosed in
a try/catch block).