RuntimeException

RuntimeException


It is an unchecked exception derived from Exception. It comprises of a big bunch of subclasses and these all are known as unchecked exceptions like ArrayIndexOutOfBoundsException, ArithmeticException, NumberFormatException, ClassCastException etc.

Following is the hierarchy.

Object –> Throwable –> Exception –> RuntimeException

Complete exception hierarchy is available at Hierarchy of Exceptions – Checked/Unchecked Exceptions.

As it represents all its subclasses, instead of using any subclass object, we can use RuntimeException straightaway. Following code explains.

RuntimeException

Observe, in the above code, catch block should have actually ArithmeticException as JVM throws ArithmeticException for the problem of division by zero. But, it is placed RuntimeException. It also handles as "super class exception can handle subclass exception also", but at performance cost. Observe the screenshot, it shows JVM throws ArithmeticException only. But catch is executed; observe our own message also.

Alternatively, you can use RuntimeException to throw as follows.

We can modify the above if structure with an anonymous object of RuntimeException as follows.

Creating User – Defined Exception

We have seen earlier another creating user-defined exception, NoBalanceException, where we extended with a checked exception, Exception class. Let us repeat the same program but by extending RuntimeException.

RuntimeException

Explanation for this program including why we need user-defined exceptions etc. is available at YesBank.java.

Leave a Reply

Your email address will not be published. Required fields are marked *