296

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?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
cchampion
  • 7,607
  • 11
  • 41
  • 51

12 Answers12

252

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.

BBdev
  • 4,898
  • 2
  • 31
  • 45
fastcodejava
  • 39,895
  • 28
  • 133
  • 186
  • 22
    I like this angle of "runtime exceptions could have been avoided by the caller". That means you (as the caller of a method) are supposed to make sure they don't even happen. Whereas checked exceptions are something that you cannot avoid and are instead required to deal with them after the fact. (And yes, since not everyone agrees with the concept of checked exceptions and many people use RuntimeException for everything, this distinction has become a bit muddled). – Thilo Nov 07 '14 at 08:22
  • 6
    Nowadays people favor unchecked RuntimeException also, because it is compatible to Java 8 Lambda processing, whereas checked exceptions of type Exception are not. – Hartmut Pfarr Aug 12 '16 at 16:18
  • 2
    I suspect the real reason people catch `RuntimeException` is because it's simple, and obviates the need to think about the differences between checked and unchecked exceptions. I think catching runtime exceptions is a terrible idea because you'll catch unrecoverable exceptions such as `NullPointerException`. – Dónal Nov 08 '17 at 11:35
233

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.

Andy White
  • 86,444
  • 48
  • 176
  • 211
  • 3
    Practically its true that "there are two types of exceptions", but why does Oracle documentations says there are three types. It consider the Error as 3rd type. I think, Error is not an Exception at all, its just Throwable (object), yea, it mimic the behaviour of runtime exceptions. What you would say about it? Oracle doc. ref. http://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html – Asif Shahzad Nov 16 '13 at 19:14
  • 4
    An Error is not meant to be caught (though it could be) generally you use errors for catching your own mistakes as youre working on new code. For instance if you have a tree if if/elseif statement, the final else might just do throw Error("wasnt expecting this condition to happen");. Generally speaking, exceptions have use cases where theyre SUPPOSED to happen, whereas errors do not have a use case and they are a bug. – Daniel Dec 17 '14 at 03:10
  • 10
    But the joke is RunTimeException itself extends Exception :D (I know this doesn't make any troubles and JVM takes care of the whole context) – Alireza Mohamadi Dec 26 '16 at 17:52
134

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 
prashant
  • 348
  • 3
  • 13
GAJJE82
  • 1,427
  • 1
  • 10
  • 7
62

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.

Yuri
  • 4,254
  • 1
  • 29
  • 46
Lawrence Dol
  • 63,018
  • 25
  • 139
  • 189
21

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).

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
sateesh
  • 27,947
  • 7
  • 36
  • 45
16

Proper use of RuntimeException?

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.

Community
  • 1
  • 1
Mahdi Esmaeili
  • 555
  • 7
  • 11
8

From oracle documentation:

Here's the bottom line guideline: 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.

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.

RuntimeExceptions are like "exceptions by invalid use of an api" examples of runtimeexceptions: IllegalStateException, NegativeArraySizeException, NullpointerException

With the Exceptions you must catch it explicitly because you can still do something to recover. Examples of Exceptions are: IOException, TimeoutException, PrintException...

iberck
  • 2,372
  • 5
  • 31
  • 41
6

In simple words, if your client/user can recover from the Exception then make it a Checked Exception, if your client can't do anything to recover from the Exception then make it Unchecked RuntimeException. E.g, a RuntimeException would be a programmatic error, like division by zero, no user can do anything about it but the programmer himself, then it is a RuntimeException.

Joe Almore
  • 4,036
  • 9
  • 52
  • 77
4

RuntimeException is a child class of Exception class

This is one of the many child classes of Exception class. RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.

The hierchy is

java.lang.Object

---java.lang.Throwable

-------java.lang.Exception

-------------java.lang.RuntimeException

jayrhd
  • 201
  • 2
  • 3
0

Exceptions are a good way to handle unexpected events in your application flow. RuntimeException are unchecked by the Compiler but you may prefer to use Exceptions that extend Exception Class to control the behaviour of your api clients as they are required to catch errors for them to compile. Also forms good documentation.

If want to achieve clean interface use inheritance to subclass the different types of exception your application has and then expose the parent exception.

F.O.O
  • 4,730
  • 4
  • 24
  • 34
0

There are two types of exception, You can recover from checked exception if you get such kind of exception. Runtime exception are irrecoverable, runtime exceptions are programming errors, and programmer should take care of it while writing the code, and continue execution of this might give you incorrect result. Runtime exceptions are about violating precondition ex. you have an array of size 10, and you are trying to access 11 th element, it will throw ArrayIndexOutOfBoundException

Bhagwati Malav
  • 3,349
  • 2
  • 20
  • 33
-1
  1. User-defined Exception can be Checked Exception or Unchecked Exception, It depends on the class it is extending to.

  2. User-defined Exception can be Custom Checked Exception, if it is extending to Exception class

  3. User-defined Exception can be Custom Unchecked Exception , if it is extending to Run time Exception class.

  4. Define a class and make it a child to Exception or Run time Exception

Aditya
  • 43
  • 9