11.1 Handling Exception

No matter how well designed a program is, there is always a chance that an error will occur during its execution. The errors occur during run time are also called execeptions. Most common execptions in a program, are :

  • Divide a number by zero.
  • Accessing an element that is out of the bounds of an array.
  • Trying to store a value into an array of an incompatible type.
  • Passing a parameter that is not in a valid range or value for a method.
  • Any many more.

When such exception encounted, java typically generates an error message and aborts the program. Before we discuss how to handle exceptions,
let us give some examples that show what can happen if an exception is not handled. Following program illustrate how an exception causes termination of execution of the program.

public class ProgramWithError
{
   public static void main(String[] args)
   {
      // Create an array with four elements.
      int[] numbers = { 10, 20, 30, 40 };

      // Attempt to read five elements.
      for (int i = 0; i <= 4; i++)
         System.out.println(numbers[i]);
   }
}

Output :

10
20
30
40
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
	at ProgramWithError.main(ProgramWithError.java:10)

Java’s Mechanism of Exception Handling

When an exception occurs, an object of a particular exception class is created. For example, in above Example, an object of the class
ArrayIndexOutOfBoundsException is created and the program terminates with the error message.

Java provides several exception classes to effectively handle certain common exceptions.

Exception Classes

Java API has an extensive hierarchy of exception classes. A small part
of the hierarchy is shown here

exception

In next section we will discuss how exceptions should be handled in java program.