Java Arithmetic Exception Example

In this example, we will learn how the ArithmeticException occurs in Java programs with an example.
This ArithmeticException is a built-in-class present in java.lang package.
From JavaDoc - The ArithmeticException has thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero" throws an instance of this class. ArithmeticException objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable.

ArithmeticException Class Diagram

Note that from the above class diagram, ArithmeticException extends RuntimeException class.

Java ArithmeticException Example

In below example, ArithmeticException occurs when an integer is divided by zero.
package com.javaguides.corejava;

public class ArithmeticExceptionExample {

    public static void main(String[] args) {
        try {
            int result = 30 / 0; // Trying to divide by zero
        } catch (ArithmeticException e) {
            System.err.println("ArithmeticException caught!");
            e.printStackTrace();
        }
    }
}

Output

ArithmeticException caught!
java.lang.ArithmeticException: / by zero
 at com.javaguides.corejava.ArithmeticExceptionExample.main(ArithmeticExceptionExample

Comments