How to Rethrow an Exception in Java
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.
- Open your text editor and type in the following Java statements:
The program attempts to access the first element of the
argsarray. 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
ArrayIndexOutOfBoundsExceptionis 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).
- Save your file as RethrowAnException.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.
When the program attempts to access the
ArrayIndexOutOfBoundsExceptionis thrown. The
catchblock 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.