How to Throw an Exception in Java

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 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
  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 of experience in training, development, and consulting in a variety of technology areas including Python, Java, C, C++, XML, JavaScript, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen has a degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.