Open In App

How to Handle a java.lang.ArithmeticException in Java?

In Java programming, the java.lang.ArithmeticException is an unchecked exception of arithmetic operations. This means you try to divisible by zero, which raises the runtime error. This error can be handled with the ArthmeticException.

ArithmeticException can be defined as a runtime exception that can occur during an arithmetic operation due to the exceptional condition. ArithmeticException is part of the java.lang package.



In this article, we will learn how to handle a java.lang.ArithmeticException in Java.

Syntax:

try {
// Code that may throw an ArithmeticException
Example: division by zero,
} catch (ArithmeticException e) {
// Exception handling code
// Handle the ArithmeticException here
This block is executed when an ArithmeticException is caught
Example: displaying an error message.

} finally {
// Optional block
}

Program to Handle a java.lang.ArithmeticException in Java

Let us understand programmatically, to handle a java.lang.ArithmeticException.






// Java program to handle a java.lang.ArithmeticException
public class GfGArithmeticException 
{
    // main method
    public static void main(String[] args) {
        int dividend = 10;
        int divisor = 0;
  
        try {
            // attempting division by zero
            int result = dividend / divisor;  
            // print the result
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            // print the error
            System.out.println("ArithmeticException occurred: " + e.getMessage());
              
        } finally {
            System.out.println("This is the example of the ArithmeticException");
              
        }
    }
}

Output
ArithmeticException occurred: / by zero
This is the example of the ArithmeticException

Explanation of the above Program:

Article Tags :