Table of contents
1.
Introduction
2.
Arithmetic Exception in Java
3.
Arithmetic Exception Structure
4.
Arithmetic Exception Constructor
4.1.
1. ArithmeticException()
4.2.
2. ArithmeticException(String message)
5.
How Arithmetic Exception Occurrence?
5.1.
1. Division by Zero
5.2.
2. Undefined Mathematical Results
5.3.
3. Overflow or Underflow
6.
Divide By 0
7.
Non-Terminating Big Decimal
8.
Handling Arithmetic Exception
8.1.
1. Using try-catch Blocks
8.2.
2. Throwing Arithmetic Exception
9.
Arithmetic Exception in Java Examples
9.1.
Example 1: Integer Division
9.2.
Example 2: Modulo Operation
9.3.
Example 3: Overflow
10.
Frequently Asked Questions
10.1.
Can Arithmetic Exceptions be prevented?
10.2.
What happens if an Arithmetic Exception is not handled?
10.3.
Are Arithmetic Exceptions checked or unchecked exceptions?
11.
Conclusion
Last Updated: Nov 3, 2024
Easy

Arithmetic Exception in Java

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java programming, the concept of exceptions is very crucial for writing robust & error-free code. Exceptions are events that disrupt the normal flow of program execution, and one common type of exception is the Arithmetic Exception. This exception is thrown when an illegal arithmetic operation is attempted, like dividing a number by zero, or when an undefined mathematical result is found. If you are a Java developer, it's crucial to understand the concept of Arithmetic Exception, like its definition, structure, constructors, & how it occurs. 

Arithmetic Exception in Java

In this article, we'll discuss Arithmetic Exceptions in detail, their definition, structure, constructors, occurrence, & handling techniques. We will also see some examples to help you understand how to deal with this exception effectively in your Java programs.

Arithmetic Exception in Java

In Java, an Arithmetic Exception is a runtime exception that is thrown when an exceptional arithmetic condition occurs. It is a subclass of the java.lang.RuntimeException class, which means it is an unchecked exception. Unchecked exceptions do not need to be explicitly declared in a method's throws clause or caught using a try-catch block, although it is still good practice to handle them appropriately.

The Arithmetic Exception is thrown in many different situations, like:

1. Dividing an integer by zero
 

2. Encountering an undefined mathematical result (e.g., the square root of a negative number)
 

3. Performing arithmetic operations that result in overflow or underflow


When an Arithmetic Exception is thrown, it indicates that an illegal arithmetic operation has been attempted, & the program cannot continue executing normally. If it is not handled properly, the exception will propagate up the call stack until it is caught or until it reaches the main method, which causes the program to terminate abruptly.

Arithmetic Exception Structure

The Arithmetic Exception class is part of the java.lang package & has the following class hierarchy:

java.lang.Object

  └── java.lang.Throwable

      └── java.lang.Exception

          └── java.lang.RuntimeException

              └── java.lang.ArithmeticException


As you can see, Arithmetic Exception is a direct subclass of RuntimeException, which in turn is a subclass of Exception. This hierarchy plays a crucial role in exception handling, as it allows you to catch & handle Arithmetic Exceptions specifically or more broadly using the superclass types.

The Arithmetic Exception class has several constructors & methods that you can use to create & handle instances of this exception. The constructors allow you to create an Arithmetic Exception object with a custom error message, while the methods inherited from the Throwable class provide functionality for obtaining information about the exception, such as the error message & the stack trace.

Some of the commonly used constructors & methods of the Arithmetic Exception class are:

1. ArithmeticException(): Creates a new Arithmetic Exception object with no detail message.
 

2. ArithmeticException(String message): Creates a new Arithmetic Exception object with the specified detail message.
 

3. getMessage(): Returns the detailed message of the exception.
 

4. printStackTrace(): Prints the stack trace of the exception to the standard error stream.

Arithmetic Exception Constructor

The Arithmetic Exception class provides two constructors that you can use to create instances of the exception. These constructors allow you to specify a custom error message that provides more information about the exception. Let's take a closer look at each constructor:

1. ArithmeticException()

   This is the default constructor for the Arithmetic Exception class. It creates a new instance of the exception without any detailed message. When an Arithmetic Exception is thrown using this constructor, it will not provide any specific information about the cause of the exception.

Example:

   ArithmeticException exception = new ArithmeticException();

2. ArithmeticException(String message)

This constructor allows you to create an Arithmetic Exception object with a custom detail message. The message parameter is a String that describes the specific reason or context of the exception. This message can be retrieved later using the getMessage() method, which is inherited from the Throwable class.

Example:

   ArithmeticException exception = new ArithmeticException("Division by zero");


When an Arithmetic Exception is thrown, you can use these constructors to create an exception object & provide a meaningful error message. The choice of constructor depends on whether you want to include a custom message or not.

Point to be remembered: It's important to note that these constructors are used when you explicitly throw an Arithmetic Exception in your code. However, in most cases, the Java runtime system will automatically throw an Arithmetic Exception when an illegal arithmetic operation is detected, & you won't need to create the exception object manually.

How Arithmetic Exception Occurrence?

Arithmetic Exception occurs when an exceptional condition arises during an arithmetic operation. Let's explore the common scenarios that can trigger an Arithmetic Exception:

1. Division by Zero

One of the most common causes of an Arithmetic Exception is dividing an integer by zero. In mathematics, division by zero is undefined & leads to an invalid operation. When attempting to divide an integer by zero in Java, an Arithmetic Exception is thrown.


Example:

   ```java
   int result = 10 / 0; // Throws an ArithmeticException
   ```

2. Undefined Mathematical Results

Certain mathematical operations can result in undefined or illegal results, leading to an Arithmetic Exception. For example, attempting to calculate the square root of a negative number or performing an operation that leads to an imaginary or infinite result will throw an Arithmetic Exception.

Example:

   double result = Math.sqrt(-1); // Throws an ArithmeticException

3. Overflow or Underflow

When performing arithmetic operations, if the result exceeds the maximum or minimum value that can be represented by the data type, an overflow or underflow condition occurs. This can happen when adding, subtracting, multiplying, or dividing numbers that are too large or too small for the given data type. In such cases, an Arithmetic Exception is thrown.

Example:

   int result = Integer.MAX_VALUE + 1; // Throws an ArithmeticException


Note: It's important to identify & handle these exceptional situations appropriately in your Java code. With the help of try-catch blocks or other exception-handling mechanisms, you can easily handle Arithmetic Exceptions & prevent your program from abruptly terminating.

Divide By 0

One of the most common scenarios that leads to an Arithmetic Exception is attempting to divide a number by zero. In mathematics, division by zero is an undefined operation & is not allowed. When you try to divide an integer by zero in Java, it will throw an Arithmetic Exception.

For example : 

public class DivideByZeroExample {
    public static void main(String[] args) {
        int number = 10;
        int divisor = 0;
        
        try {
            int result = number / divisor;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero!");
            e.printStackTrace();
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


In this example, we have a variable `number` with a value of 10 & a variable `divisor` with a value of 0. We attempt to divide `number` by `divisor` using the division operator (`/`). However, since `divisor` is zero, an Arithmetic Exception will be thrown.

To handle the Arithmetic Exception, we enclose the division operation inside a try-catch block. If an Arithmetic Exception occurs, the program will catch it and execute the code inside the catch block. In this case, we print an error message indicating that a division by zero occurred and use the `printStackTrace()` method to display the stack trace of the exception.

Output:

Error: Division by zero!
java.lang.ArithmeticException: / by zero
    at DivideByZeroExample.main(DivideByZeroExample.java:7)


The output shows that an Arithmetic Exception was thrown with the message "/ by zero", indicating that a division by zero was attempted. The stack trace provides information about where the exception occurred in the code.

Note: It's crucial to handle division by zero scenarios appropriately in your Java programs to prevent unexpected termination & provide meaningful error messages to the user.

Non-Terminating Big Decimal

Another scenario that can lead to an Arithmetic Exception is working with non-terminating decimal values using the `BigDecimal` class in Java. The `BigDecimal` class is used for precise decimal arithmetic and provides methods for performing operations on decimal numbers.

When dividing two `BigDecimal` numbers, if the division result is a non-terminating decimal, an Arithmetic Exception will be thrown. This is because the `BigDecimal` class requires a specific rounding mode to handle non-terminating decimals.

For example : 

import java.math.BigDecimal;

public class NonTerminatingDecimalExample {
    public static void main(String[] args) {
        BigDecimal number1 = new BigDecimal("1");
        BigDecimal number2 = new BigDecimal("3");
        
        try {
            BigDecimal result = number1.divide(number2);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Non-terminating decimal expansion!");
            e.printStackTrace();
        }
    }
}
You can also try this code with Online Java Compiler
Run Code

 

In this example, we create two `BigDecimal` objects, `number1` with a value of 1 & `number2` with a value of 3. We attempt to divide `number1` by `number2` using the `divide()` method. However, dividing 1 by 3 results in a non-terminating decimal (0.3333...).

By default, the `divide()` method throws an Arithmetic Exception when the division result is a non-terminating decimal. To handle this exception, we enclose the division operation inside a try-catch block. If an Arithmetic Exception occurs, the program catches the exception and executes the code inside the catch block. In this case, we print an error message indicating that a non-terminating decimal expansion occurred and use the `printStackTrace()` method to display the stack trace of the exception.


Output:

Error: Non-terminating decimal expansion!
java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
    at java.base/java.math.BigDecimal.divide(BigDecimal.java:1716)
    at NonTerminatingDecimalExample.main(NonTerminatingDecimalExample.java:10)


To avoid the Arithmetic Exception when dividing `BigDecimal` numbers, you can specify a rounding mode as an additional parameter to the `divide()` method. The rounding mode determines how the result should be rounded when a non-terminating decimal is encountered.

For example, you can use `BigDecimal.ROUND_HALF_UP` to round the result to the nearest `BigDecimal` with the specified scale:

BigDecimal result = number1.divide(number2, BigDecimal.ROUND_HALF_UP);


Note: With the help of rounding mode, you can handle non-terminating decimal divisions without encountering an Arithmetic Exception.

Handling Arithmetic Exception

When an Arithmetic Exception occurs in your Java program, it's important to handle it appropriately to prevent the program from abruptly terminating and to provide meaningful error messages to the user. Java provides several mechanisms for handling exceptions, including try-catch blocks and throwing exceptions.

1. Using try-catch Blocks

The most common way to handle an Arithmetic Exception is by using a try-catch block. You enclose the code that may throw an Arithmetic Exception inside the try block & provide the corresponding exception handling code inside the catch block.

Example:

   public class ArithmeticExceptionHandling {
       public static void main(String[] args) {
           int number = 10;
           int divisor = 0;
           
           try {
               int result = number / divisor;
               System.out.println("Result: " + result);
           } catch (ArithmeticException e) {
               System.out.println("Error: " + e.getMessage());
               e.printStackTrace();
           }
       }
   }
You can also try this code with Online Java Compiler
Run Code


Output

ERROR!
Error: / by zero
java.lang.ArithmeticException: / by zero
at ArithmeticExceptionHandling.main(ArithmeticExceptionHandling.java:7)


In this example, we enclose the division operation inside a try block. If an Arithmetic Exception is thrown, the program flow immediately transfers to the catch block. Inside the catch block, we can access the exception object (`e`) and use its methods to obtain information about the exception, such as the error message (`e.getMessage()`) and the stack trace (`e.printStackTrace()`).

Note:  By taking care of the exception, we prevent the program from abruptly terminating, and we can provide appropriate error messages or take alternative actions based on the specific situation.

2. Throwing Arithmetic Exception

In some cases, you may want to explicitly throw an Arithmetic Exception to indicate that an exceptional condition has occurred. You can use the `throw` keyword followed by an instance of the Arithmetic Exception class.

Example:

   public class ThrowingArithmeticException {
       public static int divide(int number, int divisor) {
           if (divisor == 0) {
               throw new ArithmeticException("Division by zero is not allowed!");
           }
           return number / divisor;
       }
   
       public static void main(String[] args) {
           try {
               int result = divide(10, 0);
               System.out.println("Result: " + result);
           } catch (ArithmeticException e) {
               System.out.println("Error: " + e.getMessage());
           }
       }
   }
You can also try this code with Online Java Compiler
Run Code


Output

ERROR!
Error: Division by zero is not allowed!


In this example, we have a `divide()` method that takes two integers as parameters. Inside the method, we check if the `divisor` is zero. If it is, we explicitly throw an Arithmetic Exception with a custom error message using the `throw` keyword.


In the `main()` method, we call the `divide()` method within a try-catch block. If an Arithmetic Exception is thrown, the catch block will catch it, and the appropriate error message will be displayed.

Arithmetic Exception in Java Examples

Now that we have discussed everything about arithmetic exceptions let’s look at a few more examples of Arithmetic Exceptions in Java which will help us to understand this more easily : 

Example 1: Integer Division

public class IntegerDivisionExample {
    public static void main(String[] args) {
        int number1 = 10;
        int number2 = 0;
        
        try {
            int result = number1 / number2;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero!");
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


Output

Error: Division by zero!


In this example, we attempt to divide `number1` by `number2`, which is zero. This triggers an Arithmetic Exception, which is caught by the catch block. The appropriate error message is printed.

Example 2: Modulo Operation

public class ModuloOperationExample {
    public static void main(String[] args) {
        int number1 = 10;
        int number2 = 0;
        
        try {
            int result = number1 % number2;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Modulo by zero!");
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

Error: Modulo by zero!


This example demonstrates that the modulo operator (`%`) can also throw an Arithmetic Exception when the divisor is zero. The catch block handles the exception & prints an appropriate error message.

Example 3: Overflow

public class OverflowExample {
    public static void main(String[] args) {
        int number1 = Integer.MAX_VALUE;
        int number2 = 1;
        
        try {
            int result = number1 + number2;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Overflow occurred!");
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


Output

Result: -2147483648


In this example, we add `number1` (which is the maximum value for an integer) & `number2`. The addition operation results in an overflow, as the result exceeds the maximum value that can be stored in an integer. However, unlike the previous examples, this does not throw an Arithmetic Exception. Instead, the result wraps around to the minimum value of an integer.

Always Remember: Overflow situations do not always throw an Arithmetic Exception and may lead to unexpected results. Therefore, it's crucial to be aware of the range of values that can be stored in a particular data type and handle overflow situations appropriately.

Frequently Asked Questions

Can Arithmetic Exceptions be prevented?

While Arithmetic Exceptions cannot be completely prevented, they can be handled & managed effectively using try-catch blocks or by validating input data before performing arithmetic operations.

What happens if an Arithmetic Exception is not handled?

If an Arithmetic Exception is not handled using a try-catch block or any other exception handling mechanism, the program will terminate abruptly, & the exception will propagate up the call stack until it reaches the JVM, which will then terminate the program.

Are Arithmetic Exceptions checked or unchecked exceptions?

Arithmetic Exceptions are unchecked exceptions, which means they are not required to be explicitly declared in a method's throws clause or caught using a try-catch block. However, it is still considered good practice to handle them appropriately.

Conclusion

In this article, we discussed Arithmetic Exceptions in Java, which occur when illegal arithmetic operations are performed. We learned about the definition, structure, constructors, and how Arithmetic Exceptions are thrown. We also looked into common scenarios like division by zero and non-terminating decimal expansions. 

You can also check out our other blogs on Code360.

Live masterclass