4.1 Handling Errors - Exceptions and try, catch blocks

Previous Index Next 


Java differs from most procedural languages in the way it handles errors. When an error occurs the Java application is notified by an exception message. The exception message shifts point of control of the application away from where the exception occured and moves it to a point specified by the programmer.

An exception is said to be thrown from the point where it occurred and is said to be caught at the point to which control is transferred.

Some examples of exceptions are :

In Java all exception messages are objects whose super class is Exception.

Exceptions are caught using the try and catch statements. For instance the following code attempts to convert a string to an integer. Since the string contains the letter "A" the conversion will fail.

int x;                            // declare integer x
try                               // start of try
  {
   x = Integer.parseInt("1234A"); // try convert string to integer. This fails becuase of A
   x =  x +1;                     // this code never executes because exception is thrown by line above
  }
catch (NumberFormatException e)   // catch a NumberFormatException and store it into variable e
 {
   System.out.println("Error converting number. Error was:" + e.getMessage() ); // display error message on console
   x = 0;                         // set x = 0;
 }
Exceptions can be explicitly thrown using the throw statement. For example:
throw new Exception("This is a Test exception.");
The Java compiler will detect exceptions that are thrown by the code and will not compile if there is not a try..catch block to handle these exceptions.

The catch statement will only catch exceptions of the type specfied or sub-classes of the type specified. In the number conversion example above only NumberFormatException exceptions and sub-classes of NumberFormatException would be caught. All other exceptions would be allowed through. Since the Exception class is the super-class for all the exceptions, a catch statement that catches Exception object will catch all exceptions.

Mutilple catch statements can be coded. This allows specific exceptions to be caught whilst other are let through.



Sources 1