How to Handle Exceptions in Java

  • google plus

In Brief...

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.

Take our Introduction to Java Training course for free.

See the Course Outline and Register

Instructions

  1. Open your text editor and type in the following Java statements:
    Java Source for Handle Exceptions
    The program attempts to access the first element of the args array. This array contains any parameters that might have been coded on the command line. If no parameters were provided, then the args array 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 try block. The try block is followed by a catch block. Should an exception occur, control will automatically branch to the catch block.
  2. Save your file as HandleExceptions.java.
  3. 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.
    Compile Source for Handle Exceptions
  4. Type in the command to run your program without providing a command line parameter and hit Enter.
    Run for Handle Exceptions
    The ArrayIndexOutOfBoundsException was thrown because the args array is empty. The program caught the exception and displayed an error message.
  5. Type in the command to run your program and be sure to enter the parameter ("Stephen" in this example) and hit Enter.
    Run for Handle Exceptions
    The program ended normally because the args array had one item. Therefore, the first item could have been referenced without incurring an exception.

Related Video

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss