How to Handle Exceptions in Java
An exception is an error condition that is raised, or thrown, by a Java method. The exception can be handled by a Java program that has called the method. To handle the exception, the program "catches" the exception. To understand how to handle an exception in Java, follow these five steps.
- Open your text editor and type in the following Java statements:
The program attempts to access the first element of the
argsarray. This array contains any parameters that might have been coded on the command line. If no parameters were provided, then the
argsarray is empty and the attempt to access the first element will result in an
ArrayIndexOutOfBoundsException. Notice that the code that accesses the array element is in a
tryblock is followed by a
catchblock. Should an exception occur, control will automatically branch to the
- Save your file as HandleExceptions.java.
- Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter.
- Type in the command to run your program without providing a command line parameter and hit Enter.
ArrayIndexOutOfBoundsExceptionwas thrown because the
argsarray is empty. The program caught the exception and displayed an error message.
- Type in the command to run your program and be sure to enter the parameter ("Stephen" in this example) and hit Enter.
The program ended normally because the
argsarray had one item. Therefore, the first item could have been referenced without incurring an exception.