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.
- Open your text editor and type in the following Java statements:
The IllegalArgumentExceptionis thrown at line 15 within thedivideIntmethod. 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 thedivideIntmethod 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. - Save your file as ThrowAnException.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 and hit Enter.

The first call to the divideIntmethod is successful. The second call, using a divisor of 0, causes theIllegalArgumentExceptionto be thrown. The message passed to the constructor is displayed in the output.
