Exceptions

The concept of Exception in basic to Java and is used in a number of contexts in addition to I/O. In an effort to help the programmer write code that is reliable, Java provides a general mechanism that enables the programmer to look for possible run time errors and to take appropriate action when they occur, rather than letting the program continue until possibly crashing or producing erroneous results.

Java provides a number of language-defined exceptions, but the programmer can also create new exception types for the particular application. In this discussion, we will only consider the handling of built-in exceptions.

When a method is defined, the definition may specify that the method will throw a particular type of Exception. Then, when one uses that method, one must do so within a try/catch construct.:

try 
  { 
    statements that can throw an exception 
  }  // end try
catch ( Specific_Type_of_Exception except_instance )
  {
     statements that take appropriate action 
  }  // end catch

For example:

try 
  { 
    c = b / a;
  }  // end try
catch ( DivideByZeroException exception )
  {
     System.err.println ( "Attempted to divide by zero");
     return;
  }  // end catch

Since a given statement can generate more than one kind of exception, Java permits you to include multiple catch constructs. You may also include a finally construct after all the catch constructs; it will be executed regardless of whether an exception is thrown. A freequent use is to release resources.