How to Throw an Exception in Java

See Java: Tips and Tricks for similar articles.

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.

  1. Open your text editor and type in the following Java statements:Java Source for Throwing an ExceptionThe 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 ExceptionThe 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.