3.1.8 Runtime Exceptions3.1.7 Exceptions Thrown by Handlers3.1 Exception Handling3.1.9 When Not to Use Exceptions

3.1.8 Runtime Exceptions

The Java standard library defines the following hierarchy of exceptions:  

   Exception
     |
     +-- RuntimeException
     |     |
     |     +-- ArithmeticException
     |     +-- IndexOutOfBoundException
     |     +-- NullPointerException
     |     +-- ...
     +-- IOException
     +-- InterruptedException
     +-- ClassNotFoundException
     +-- ...

Example  The Java standard class Thread provides the method
   public static void sleep(long ms) throws InterruptedException

which lets the program sleep (temporarily cease execution) for the specified number of milliseconds. This sleep may be interrupted in which case an InterruptedException is thrown. We may thus let the current program sleep for 100 milliseconds by a call

  try
  {
    Thread.sleep(100);
  }
  catch(InterruptedException e)
  {
    System.out.println(``Someone woke me up.'');
  }

This hierarchy has a sub-hierarchy of  runtime exceptions, i.e., of all subclasses of RuntimeException. These exceptions are special in two senses:  

  1. Runtime exceptions are generated as the results of illegal JVM instructions (not as the results of throw statements):
  2. Runtime exceptions need not be declared in method headers; they can therefore be propagated by the main method to the JVM.

As an example, a program that executes a division by zero instruction  

   public class Main
   {
     public static void main(String[] args)
     {
       int i = 0;
       int j = 1/i;
     }
   }

aborts with the following exception (i.e., the JVM catches the exception and prints the corresponding information):

  Exception in thread "main" 
    java.lang.ArithmeticException: / by zero
          at Main.main(Main.java:6)

If we wish, we may explicitly catch runtime exceptions as in

   try
   {
     int i = 0;
     int j = 1/i;
   }
   catch(ArithmeticException e)
   {
     System.out.println("Arithmetic Exception: " + e.getMessage());
   }

The Exception method getMessage (which is expected to be overwritten by any subclass of Exception) describes the exception in more detail (such as "/ by zero" in above case).

The programmer may also declare own runtime exceptions as subclasses of RuntimeException and explicitly raise them by throw statements. In this case, the exception type needs not be declared in method headers. However, we do not recommend this as a general strategy because the information which exceptions are thrown by a method has to be considered as part of the method specification and should therefore be made explicit in the method header.


© Wolfgang Schreiner; February 3, 2005

3.1.8 Runtime Exceptions3.1.7 Exceptions Thrown by Handlers3.1 Exception Handling3.1.9 When Not to Use Exceptions