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.

public class Rose
{
  public static void main(String args[])
  {
     try
     {
        int x = 10/0;
     }
     catch(RuntimeException e)
     {
         System.out.println("Exception is handled successfully. " + e);
     }
   }
}

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.

       int sales = 10, working_days = 0;
       if(working_days == 0)
       {
         RuntimeException e = new RuntimeException(“Working days cannot be zero.”);
         throw e;
       }

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

       if(working_days == 0)
       {
          throw new RuntimeException(“Working days cannot be zero.”);
       }

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.

class NoWorkingDays extends RuntimeException
{
  public NoWorkingDays(String message)
  {
    super(message);
  }
}
public class Office
{
  public static void main(String args[])
  {
    int sales = 10, working_days = 0;
    if(working_days == 0)
    {
      RuntimeException e = new RuntimeException("Working days cannot be zero.");
      throw e;
    }
    else
    {
        System.out.println("Avg. sales is " + (sales/working_days));
    }
  }
}

RuntimeException

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

Leave a Comment

Your email address will not be published.