DEV Community

Aglowid It Solutions
Aglowid It Solutions

Posted on

Handling the Arithmetic Exception in Java

Exception Handling is an important aspect of any programming language; the same applies to Java. It enables developers to manage undesirable outcomes or situations during runtime. One such common exception in Java is the ArithmeticException.

Understanding ArithematicException in Java

ArithmeticException is a subclass of RuntimeException class and is generally raised by JVM when the developer performs any incorrect arithmetic equation where the result of the operation is not a valid numeric value or the operation is not mathematically possible. For general reference, anything that your graphing or scientific calculators cannot compute will be thrown as an ArithmeticException at runtime by the JVM.

Importance of resolving ArithmeticException in Java

Most developers often overlook arithmetic exceptions in Java since it seems like a minor issue at first glance. However, resolving arithmetic exceptions is crucial if you want your Java application to run smoothly and carry out important calculations to deliver accurate results. Here are the benefits of resolving Arithmetic Exceptions in Java –

Prevents/Reduces Program Crashes

Unchecked Arithmetic Exceptions lead to unexpected program crashes, leading to unforeseen downtimes and adding to the unreliability of your software. By implementing proper arithmetic exception-handling techniques, we can save the software from running into termination while improving your business's security, stability and reliability.

Debugging and Troubleshooting

Arithmetic Exceptions can help identify and find bugs or logical errors in our Java codebase. Resolving such exceptions gives practical insights into the exact locations and root causes of that error. This eases the process of resolving and debugging the arithmetic errors.

Maintaining Data Integrity

Unchecked ArithmeticExceptions can ruin the integrity of your data and calculations. For instance, dividing a number by zero will throw an error in the system and may cause the system to terminate. You can set up reliable fallback mechanisms, validate input data or apply alternative calculations when handling Arithmetic Expressions in Java.

Maintaining Code Robustness

Resolving arithmetic exceptions is a must-have skill for Java developers. It differentiates experienced and skilled Java developers from others. It also reflects their commitment to producing high-quality software and providing a stable environment to their users.

How to handle ArithmeticException in Java?

The ArithmeticException class is a sub-class of RuntimeException, which fall under the category of unchecked exceptions in Java. There are two most frequent and obvious causes of running into an ArithmeticException – performing an arithmetic equation with zero as the denominator or non-terminating big decimal numbers that don't provide a definitive end numerical value.

Division of a number by an integer zero

When you attempt to divide a number by zero in mathematics, the answer is undefined; similarly, when you try to divide a number by zero in a programming language like Java, the operation is considered invalid. This error is not caught during the compile time, as dividing a number by 0 is a valid mathematical expression. However, at runtime, it would throw an ArithmeticException to indicate an invalid decision.

Take this code snippet, for instance –

int numerator = 10; 

int denominator = 0; 

int result = numerator / denominator; // Throws ArithmeticException
Enter fullscreen mode Exit fullscreen mode

Here as you can see, we defined the numerator as 10 and the denominator as 0. Since division by 0 is not a valid arithmetic calculation, the JVM throws an ArithmeticException when executing this code. Such execution halts the natural flow of the program and indicates an exceptional occurrence in the system. Your program will terminate after the method throws an error message like -

Exception in thread "main" java.lang.ArithmeticException: / by zero 

at MyClass.main(MyClass.java:4)
Enter fullscreen mode Exit fullscreen mode

There are three ways to handle the division of a number by an integer zero ArithmeticException –

  1. Validating the value of the divisor beforehand
  2. Try and Catch Method

Validating the value of the divisor beforehand

One of the best and most efficient ways to avoid ArithmeticException is to ensure that the denominator's value isn't 0 before running your code. However, if your code has data points where such situations are bound to rise, you should validate the value of the divisor before you use it.

public class Main { 

  public static void main(String[] args) { 

    int x=100,y=0; 

    if(y!=0){ 

      int z= x/y; 

        System.out.println("Result : " + z); 

    }else{ 

      System.out.println("undefined (division by zero)"); 

    } 

  } 

}
Enter fullscreen mode Exit fullscreen mode
  • First, we define the value of our two integers – x=100 and y=0.
  • Next, we validate if the 'y' value equals zero using the 'y!= 0' condition.
  • If the condition is true (y is not zero), the code will get inside the if block.
  • - We have the division operation 'x/y' under the 'if' block and the result will be stored in the integer variable 'z'.
  • - After going through the division, the code will print out the result by concatenating the ‘Result’ variable using System.out.printIn.
  • If the condition is false (y != 0), the code would move to the élse’ block.
  • Here the code would print the string 'undefined', reflecting that the error of dividing zero has occurred.
  • The execution would end after executing the ‘main thread.

Try and Catch Method

Now let's take the same example but set up exception handling so that the system doesn't crash when we divide the numerator with 0 as the denominator.

int numerator = 10; 

int denominator = 0; 

try { 

    int result = numerator / denominator; 

    System.out.println("Result: " + result); 

} catch (ArithmeticException e) { 

    System.err.println("Invalid: Division by zero is not allowed."); 

}
Enter fullscreen mode Exit fullscreen mode
  • Similar to the previous example, we will keep the numerator as 10 and the denominator as 0.
  • We will introduce the 'try' block to encapsulate the division operation 'numerator/denominator'.
  • Do the calculation of the arithmetic expression inside the ‘try’ block and store the result as the ‘result’ variable.
  • When we run the code, we will run into the same ArithmeticException, but instead of the app crashing, the control would switch to the set ‘catch’ block.
  • The ‘catch’ block needs to specify the kind of exception it is catching; in our case, it will be ArithmeticException.
  • Once the code executes inside the 'catch' block, we command the software to print an error message using 'System.err.printIn()’. This indicates that the arithmetic equation of dividing a number by 0 is not allowed.
  • This allows the program to identify such data points and catch the exceptions while letting the normal value integers be executed without disrupting the flow of your application.

2. Non-Terminal Big Decimal

Java has a special big decimal class that performs accurate arithmetic calculations for numbers with decimal values. This is a non-terminal class, and unlike ‘float or ‘double data types, BigDecimal can accurately manipulate decimal numbers without impacting the precision level of the data. This is known as floating point arithmetic and is used by financial sectors or enterprises that require the manipulation of large numbers with accuracy.

The main issue with the floating arithmetic method is failing to mention a limit or scale with a round-off method for operations that can produce an output with infinite decimal numbers. Having infinite decimal numbers will lead the Java software to throw an ArithmeticException error.

*For instance – *

// import statement    
import java.math.BigDecimal;   
public class ArithmeticException2 
{   
// main method   
public static void main(String[] args)   
var a = new BigDecimal(“1.7”) 
var b = new BigDecimal(“9.4”) 
var c = a.divide(b); 
System.out.println(c); 
  }   
}   
Enter fullscreen mode Exit fullscreen mode

Here we are trying to declare two BigDecimal variables – var a (1.7) and var b(9.4). When we try to divide var a by var b, we get a result like - 0.18085106382978723… which goes on endlessly in a repetitive sequence. Here the BigDecimal::divide method fails to return an exact value as it is programmed to, and the JVM throws ArithmeticException.

There are two ways to prevent ‘ArithemeticException' for non-terminal excepts when working with the BigDecimal approach to Java. They are –

  • Establishing a Rounding Mode
  • Using the Try-Catch Blocks

Establishing a Rounding Mode

You must have been taught as a general practice in school math classes to round off high decimal numbers like .457 to .46. Depending on how many decimal points were permissible, you would round off the answer accordingly. If the number next to the right of the last number in your range is greater than or equal to 5, add +1 to the last number. In case it is less than 5, it remains untouched.

Similarly, to handle the non-terminal big decimal arithmetic exception in Java, you can use the several round-off models present in Java, such as 'RoundingMode.DOWN ’ or RoundingMode.HALF_UP.

Suppose we use RoundingMode.HALF_UP method would look like this –

import java.math.BigDecimal; 
import java.math.RoundingMode; 
public class RoundingModeExample { 
    public static void main(String[] args) { 
        BigDecimal number1 = new BigDecimal("10.555"); 
        BigDecimal number2 = new BigDecimal("3"); 
        // Set the desired rounding mode 
        BigDecimal result = number1.divide(number2, 2, RoundingMode.HALF_UP); 
        System.out.println("Result: " + result); 
    } 
} 
Enter fullscreen mode Exit fullscreen mode

We used the HALF_UP rounding method, which means it will round up the decimal to the nearest neighbour in the fraction's value is greater than or equal to 0.5. Hence, when you divide 10.555/3 generally, you'd get the answer – 3.518333333.. and so on. Using this method, the output that we get will be –

Result: 3.52

Since we used a scale of 2, it indicated the number of decimal places we were willing to go up to and since the third decimal value was 8 (>5), we rounded up the decimal point to give up the final output – 3.52.

Using the Try and Catch Model

For the 'ArithmeticException' of BigDecimal non-terminal numbers, you can also use the Try and Catch model as we did for the divided by zero problems. You can catch and handle the exception that could occur when performing complex arithmetic operations. The try-and-catch method can help display an error message in place of the app crashing, and users can continue operating the system without interruptions.

Here is an example of how you can make use of try and catch model for non-terminal ‘BigDecimal' arithmetic exceptions in Java –

import java.math.BigDecimal; 
import java.math.RoundingMode; 
public class Example { 
    public static void main(String[] args) { 
        BigDecimal numerator = new BigDecimal("1"); 
        BigDecimal denominator = new BigDecimal("3"); 
        try { 
            BigDecimal result = numerator.divide(denominator, 10, RoundingMode.HALF_UP); 
            System.out.println("Result: " + result); 
        } catch (ArithmeticException e) { 
            System.out.println("Error: Non-terminating decimal expansion occurred."); 
        } 
    } 
} 
Enter fullscreen mode Exit fullscreen mode

Here we use two BigDecimal numbers, 1 as the numerator and 3 as the denominator. By using the numerator.divide(denominator, scale, rounding mode)' method; we are specifying a scale of 10 decimal places using the RoundingMode.HALF_UP method. We wrapped the division operation within the try block to handle the exception. The catch block will be triggered if ArithmeticException occurs during the division process. The catch block will catch this exception and print an error message that indicates a non-terminating decimal expansion occurred.

Wrapping Up!
This is your ultimate guide on handling the ArithmeticException in Java software and applications. Hire Java developers from a reliable IT company that follows these best practices and does not neglect any exceptions when optimizing your Java performance.

Top comments (0)