Creation of code for an exception should include the following components:
- The program should try to execute the statements contained within a block of code. (A try block of code is a group of one or more statements surrounded by braces after the keyword try.)
- If an exceptional condition within that block is detected, the exception object of a specific type is thrown out. When an exceptional condition occurs within a method, the method may instantiate an exception object and hand it off to the runtime system. This is accomplished using the throw keyword. To be useful, the exception object should contain information about the exception, including its type and the state of the program when the exception occurred.
- Catch should be used and the exception object processed, using code. The runtime system begins its search with the method in which the exception occurred and searches backward through the call stack until it finds a method that contains an appropriate exception handler (catch block).
- An exception handler is appropriate if the type of the exception thrown is the same as the type of exception handled by the handler, or is a subclass of the type of exception handled by the handler.
- Optionally a block of code should be executed, designated by the finally keyword, which needs to be executed regardless of the occurrence of an exception. (Code in the finally block is normally used to perform some type of cleanup or closure of an opened file.)
A simple program that requires exception handling follows:
import java.io.*;
public class HelloName{
public static void main(String args[] ) {
final int LENGTH = 255;
byte buffer[] = new byte [LENGTH]
System.out.print(“Enter your name: “);
try{
System.in.read(buffer, 0, LENGTH);
}
catch (Exception e) { }
String name = new String(buffer);
System.out.println(“Hello, “ + name.trim() + “!”)
}
}