How to Rethrow an Exception in Java

  • google plus

In Brief...

An exception can be rethrown in a catch block. This action will cause the exception to be passed to the calling method. If the rethrow operation occurs in the main method then the exception is passed to the JVM and displayed on the console. The purpose of the rethrow operation is to get the attention of the outside world that an exception has occurred and at the same time perform any contingency logic (such as logging) in the catch block. To learn how to rethrow an exception in Java, follow these four 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 Rethrowing an Exception
    The program attempts to access the first element of the args array. This array is populated with any command line parameters that were present when the program was started. If no command line parameters were provided by the console user, then an ArrayIndexOutOfBoundsException is thrown at runtime. This exception is caught by the program. A log entry is produced, then the exception is rethrown to the JVM (see line 9).
  2. Save your file as RethrowAnException.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 Rethrow Exception
  4. Type in the command to run your program without providing a command line parameter and hit Enter.
    Run for Test Rethrow Exception
    When the program attempts to access the args array, an ArrayIndexOutOfBoundsException is thrown. The catch block generates a log message to the console and then rethrows the exception to the JVM. The JVM displays the call stack trace for the exception on the console.

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