How to Throw an Exception in Java

  • google plus

In Brief...

You can throw an exception in Java by using the throw keyword. This action will cause an exception to be raised and will require the calling method to catch the exception or throw the exception to the next level in the call stack. To learn how to throw an exception in Java, follow these four steps.

Instructions

  1. Open your text editor and type in the following Java statements:
    Java Source for Throwing an Exception
    The IllegalArgumentException is thrown at line 15 within the divideInt method. Two calls are performed to the method. The method calls are executed in a try catch block. If an exception is thrown, then the message that was passed to the constructor of the exception will be displayed. The first call to the divideInt method will be successful. The second call passes a 0 for the divisor and will cause an exception to be thrown at runtime. A divisor of 0 would cause an arithmetic exception to be thrown by the JVM (Java Virtual Machine). Of course, we could allow the arithmetic exception to be raised but the approach we're taking permits us to validate the divisor before attempting the ill-fated arithmetic.
  2. Save your file as ThrowAnException.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.
  4. Type in the command to run your program and hit Enter.
    Compile Source for Throw ExceptionRun for Throw Exception
    The first call to the divideInt method is successful. The second call, using a divisor of 0, causes the IllegalArgumentException to be thrown. The message passed to the constructor is displayed in the output.

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