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.
IllegalArgumentExceptionis thrown at line 15 within the
divideIntmethod. 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
divideIntmethod 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.
divideIntmethod is successful. The second call, using a divisor of 0, causes the
IllegalArgumentExceptionto be thrown. The message passed to the constructor is displayed in the output.