Arithmetic error java

The ArithmeticException in Java is thrown by the JVM when an arithmetic operation creates an exceptional condition.

Introduction

Arithmetic is at the core of every program and every programming language in existence. From integer and floating-point arithmetic all the way down to bitwise and pointer arithmetic, these mathematical operations translate into machine instructions which execute with thundering speeds and manipulate the state of software applications used across all sorts of different domains. Most modern programming languages have a dedicated category of errors or exceptions for dealing with all the peculiar cases and problematic conditions that may arise while performing these arithmetic operations.

ArithmeticException & Why it is an Unchecked Exception

In Java, any arithmetic operation which creates an exceptional condition makes the Java Virtual Machine throw the ArithmeticException exception [1]. Generally speaking, anything that a scientific calculator isn’t able to process would throw this exception. At a lower level, certain rules and constraints are imposed by the programming language itself, so if any of these are broken, the ArithmeticException exception will emerge.

ArithmeticException inherits from the RuntimeException class which means it is an unchecked, runtime exception [2]. This is due to a language design decision made to reduce the exception handling clutter that would otherwise arise with the high frequency of arithmetic operations, but more importantly because throwing and propagating arithmetic exceptions wouldn’t make sense for the majority of cases, which in practice are the result of logical programming errors that need to be refactored, rather than exceptions that need to be handled. Consequently, Java doesn’t require ArithmeticException instances to be checked and will only let them manifest at runtime.

How to Handle ArithmeticException

To prevent the ArithmeticException exception in Java, one should diligently implement methods with arithmetic operations and ensure that they are correct from a mathematical and a semantical standpoint. If and when encountered, the ArithmeticException exception should instigate refactoring of the problematic code, and only in rare and justified cases, the exception should be explicitly handled.

ArithmeticException Examples

Division by zero (integer arithmetic)

Dividing a real number by zero is one of those mathematical operations that seem very simple but do not have a clean and definitive answer. The result of this operation is formally considered to be undefined, as any attempt at a definition leads to a contradiction [3]. Since this is a special case of the division operation, Java treats it as an exceptional condition and throws the ArithmeticException exception whenever it encounters it at runtime.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package rollbar;

public class DivisionByZero {

 public static void main(String... args) {
   int a = 50, b = 0;
   int c = divideAndSquare(a, b);
   System.out.println(c);
 }

 static int divideAndSquare(int x, int y) {
   int z = x / y;
   return z * z;
 }
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at rollbar.DivisionByZero.divideAndSquare(DivisionByZero.java:12)
    at rollbar.DivisionByZero.main(DivisionByZero.java:7)

Preferred approach

The proper way to deal with division by zero is to make sure that the divisor variable is never zero, or when the input cannot be controlled and there is a possibility of zero manifesting itself in the equation, treating that as one of the expected options and resolving it accordingly. This usually means testing (validating) the value of the divisor before using it, as shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package rollbar;

public class DivisionByZero {

 public static void main(String... args) {
   int a = 50, b = 0;
   if (b != 0) {
     int c = divideAndSquare(a, b);
     System.out.println(c);
   } else {
     System.out.println("undefined (division by zero)");
   }
 }

 static int divideAndSquare(int x, int y) {
   int z = x / y;
   return z * z;
 }
}
undefined (division by zero)

Alternative approach

As with any other exception, it is possible to catch the ArithmeticException inside a try-catch construct, but this should generally be avoided as it creates memory overhead and understates the importance of validating input values and working with a bounded set of parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package rollbar;

public class DivisionByZero {

 public static void main(String... args) {
   int a = 50, b = 0;
   try {
     int c = divideAndSquare(a, b);
     System.out.println(c);
   } catch (ArithmeticException e) {
     System.out.println(e.getMessage());
   }
 }

 static int divideAndSquare(int x, int y) {
   int z = x / y;
   return z * z;
 }
}
/ by zero

Division by zero doesn’t always throw ArithmeticException

It is important to be aware that division by zero in the context of floating point numbers does NOT trigger the ArithmeticException. This is because the IEEE 754 standard [4] defines division by zero in floating point arithmetic as ±Infinity and the JVM specification follows this standard [5]. As it can be seen in the example below, setting the operand types to the double floating point number type, results in the positive Infinity constant [6] being assigned to the variable z, which then multiplied by itself yields Infinity again.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package rollbar;

public class DivisionByZeroFP {

 public static void main(String... args) {
   int a = 50, b = 0;
   double c = divideAndSquare(a, b);
   System.out.println(c);
 }

 static double divideAndSquare(double x, double y) {
   double z = x / y;
   return z * z;
 }
}
Infinity

Non-terminating decimal expansion (floating point arithmetic)

Many Java software applications used in the financial sector or otherwise requiring the representation and manipulation of large numbers with great precision, rely on accurate floating point arithmetic and the use of specialized classes such as BigDecimal [7]. Working with these classes requires special attention to detail so as to avoid certain mistakes and prevent erroneous results. As an example, failing to specify a scale with a rounding mode to any operation that may produce a number with an infinite decimal expansion (such as 1.3333…) [8] will throw an ArithmeticException.

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.math.BigDecimal;

public class NonTerminatingDecimalExpansion {

 public static void main(String... args) {
   var a = new BigDecimal("1.8");
   var b = new BigDecimal("9.2");
   var c = a.divide(b);
   System.out.println(c);
 }
}
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
    at java.base/java.math.BigDecimal.divide(BigDecimal.java:1723)
    at rollbar.NonTerminatingDecimalExpansion.main(NonTerminatingDecimalExpansion.java:10)

The code in the example above declares two BigDecimal instances with the values of 1.8 and 9.2, and tries to divide the first one by the second one. However, since the result of 1.8/9.2 is 0.195652173913043478260869565217391304347826086…. with an endlessly repeating sequence, the BigDecimal::divide method is unable to return an exact value and the JVM throws an ArithmeticException. As the Java documentation for BigDecimal suggests:

“…In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3. If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations.”

The way out of this issue is to specify a scale of the quotient to be returned and a rounding policy to apply to the calculated result. One of the ways to do this is by invoking the overridden version of the BigDecimal::divide method which takes two additional parameters for scale and rounding mode, as demonstrated below. Now the resulting computation is a valid number rounded down to 4 decimal places, as explicitly specified.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class NonTerminatingDecimalExpansion {

 public static void main(String... args) {
   var a = new BigDecimal("1.8");
   var b = new BigDecimal("9.2");
   var c = a.divide(b, 4, RoundingMode.DOWN);
   System.out.println(c);
 }
}
0.1956

Safe type casts & putting ArithmeticException to good use

In rare instances, particularly when designing libraries for use by other programs and APIs, ArithmeticException can effectively be used as a safeguard against undesired results and consequences. One such case is numeric type conversions (aka. casts), which Java allows to be done in either direction, from a smaller capacity type to a larger one and vice versa. Casting from a larger to a smaller capacity type is known as downcasting, which is a process where certain information may be lost if the value is larger than what the smaller type can hold. As a specific example, below is a small program casting the maximum value a long type can hold to an integer, i.e., int type. The resulting value here is -1 which is not representative of nor close to the initial value in any way.

package rollbar;

public class SafeNumericTypeCast {

 public static void main(String... args) {
   long l = Long.MAX_VALUE;
   int i = (int) l;
   System.out.println(l);
   System.out.println(i);
 }
}
9223372036854775807
-1

To avoid this from happening, an explicit check can be performed to see whether the input value falls within the boundaries of what the target type can hold, as shown below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package rollbar;

public class SafeNumericTypeCast {

 public static void main(String... args) {
   long l = Long.MAX_VALUE;
   int i = longToInt(l);
   System.out.println(l);
   System.out.println(i);
 }

 static int longToInt(long l) {
   if (l > Integer.MAX_VALUE || l < Integer.MIN_VALUE) {
     throw new ArithmeticException(l + " cannot be safely cast to int.");
   }
   return (int) l;
 }
}
Exception in thread "main" java.lang.ArithmeticException: 9223372036854775807 cannot be safely cast to int.
at rollbar.SafeNumericTypeCast.longToInt(SafeNumericTypeCast.java:14)   at rollbar.SafeNumericTypeCast.main(SafeNumericTypeCast.java:7)

This naive and straightforward approach will prevent unsafe casts by triggering the ArithmeticException exception, which is a reasonable solution in this scenario. A more succinct and idiomatic way of accomplishing the same would be to use the native Java method Math::toIntExact which essentially does the same under the hood and makes the type cast safe, i.e., checked.

package rollbar;

public class SafeNumericTypeCast {

 public static void main(String... args) {
   long l = Long.MAX_VALUE;
   int i = Math.toIntExact(l);
   System.out.println(l);
   System.out.println(i);
 }
}
Exception in thread "main" java.lang.ArithmeticException: integer overflow
    at java.base/java.lang.Math.toIntExact(Math.java:1080)
    at rollbar.SafeNumericTypeCast.main(SafeNumericTypeCast.java:7)

Conclusion

Arithmetic operations are some of the most frequently encountered operations found in programming code. Java has a dedicated type of exception called ArithmeticException for dealing with exceptional conditions that arise from these operations. The key to preventing the ArithmeticException is being very explicit and deliberate in dealing with special cases such as integer division by zero and non-terminating decimal expansions in floating point arithmetic. Practical examples of these cases alongside possible ways and mechanisms for dealing with them are presented in this article. Finally, a software design scenario where the ArithmeticException exception can be used in a purposeful and beneficial manner is explored, in the context of safe numeric type conversions.

Track, Analyze and Manage Errors With Rollbar

Managing Java errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

References

[1] Oracle, 2021. ArithmeticException (Java SE 17 & JDK 17). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ArithmeticException.html. [Accessed Jan. 25, 2022]

[2] Oracle, 2021. Unchecked Exceptions — The Controversy (The Java™ Tutorials > Essential Java Classes > Exceptions). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html. [Accessed Jan. 25, 2022]

[3] Mathworld.wolfram.com, 2022. Division by Zero — from Wolfram MathWorld. Wolfram Research, Inc. [Online]. Available: https://mathworld.wolfram.com/DivisionbyZero.html. [Accessed Jan. 25, 2022]

[4] Wikipedia.org, 2022. IEEE 754 — Wikipedia. Wikimedia Foundation, Inc. [Online]. Available: https://en.wikipedia.org/wiki/IEEE_754. [Accessed Jan. 25, 2022]

[5] Oracle, 2021. The Java® Language Specification. Chapter 15. Expressions. Division Operator /. Oracle Corporation and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/specs/jls/se17/html/jls-15.html#jls-15.17.2. [Accessed Jan. 25, 2022]

[6] Oracle, 2021. Double (Java SE 17 & JDK 17). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Double.html#POSITIVE_INFINITY. [Accessed Jan. 25, 2022]

[7] Oracle, 2021. BigDecimal (Java SE 17 & JDK 17). Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/math/BigDecimal.html. [Accessed Jan. 25, 2022]

[8] Encyclopedia of Mathematics, 2021. Infinite decimal expansion — Encyclopedia of Mathematics. European Mathematical Society. [Online]. Available: http://encyclopediaofmath.org/index.php?title=Infinite_decimal_expansion&oldid=33414. [Accessed Jan. 25, 2022]

Java ArithmeticException

Introduction to Java ArithmeticException

Java Arithmetic Exception is a kind of unchecked error or unusual outcome of code that is thrown when wrong arithmetic or mathematical operation occurs in code at run time. A runtime problem, also known as an exception, occurs when the denominator is integer 0, the JVM is unable to evaluate the result, and therefore the execution of the program is terminated, and an exception is raised. The point at which exception has raised the program terminates but code earlier to that is executed, and the result is shown.

The base class of java arithmetic exception is lang.ArithmeticException, which comes under java.lang.RuntimeException.

Structure of ArithmeticException in Java

Structure of base Class ArithmeticException:

Structure of base Class ArithmeticException

Constructor of ArithmeticException

1. ArithmeticException(): Define an Arithmetic Exception with no parameter passed or with not any detailed message.

2. ArithmeticException(String s): Define an ArithmeticException with one parameter passed.

s: s is the detailed message 

How ArithmeticException Work in Java?

Below are the two situations that can lead to Java ArithmeticException:

  • Division of a number by Zero which is not defined and an integer.
  • Non-terminating long decimal numbers byBig Decimal.

1. Division of a Number by an Integer Zero

An arithmetic exception in java is thrown when we try to divide a number by zero. Below is the java code to illustrate the operation:

Example #1

Code:

package com.java.exception;
public class ArithmeticException
{
void division(int a,int b)
{
int c=a/b;
System.out.println("Division has been successfully done");
System.out.println("Value after division: "+c);
}
public static void main(String[] args)
{
ArithmeticException ex=new ArithmeticException();
ex.division(10,0);
}
}

Output:

Java ArithmeticException Example 1

  • lang.ArithmeticException: Exception thrown by java language during division
  • / by zero: It is the detailed message given to the class ArithmeticException while generating the ArithmeticException instance.

As we have divided 10 by 0, where 0 is an integer and is undefined, it throws above arithmetic exception.

Example #2

Code:

//package com.java.exception;
public class ArithmeticException
{
void division(int a,int b)
{
int c=a/b;
System.out.println("Division of a number is successful");
System.out.println("Output of division: "+c);
}
public static void main(String[] args)
{
ArithmeticException ex=new ArithmeticException();
ex.division(10,5);
}
}

Output:

Java ArithmeticException Example 2

2. Non-Terminating Long Decimal Numbers by Big Decimal

Java has a BigDecimal class that represents decimal numbers up to a large number of precision digits. This class of java also has some set of functionalities that are not available in the primitive data types, for example, integer, doubles, and floats. These functionalities provide rounding off the decimal numbers

Below is the code for illustration:

Example #1

Code:

//package com.java.exception;
import java.math.BigDecimal;
public class ArithmeticException
{
public static void main(String[] args)
{
BigDecimal a=new BigDecimal(1);
BigDecimal b=new BigDecimal(6);
a=a.divide(b);
System.out.println(a.toString());
}
}

Output:

Java ArithmeticException Example 1

In the java code written above, as the big decimal class doesn’t know what to be done with the division output, hence it throws or shows an arithmetic exception in the output console.

It throws an exception with a detailed message “Non-terminating decimal expansion, no exact representation.”

One possible way out for the above big decimal class is to state the number of decimal places we need from a big decimal number and then limit the value to a definite number of decimals. For example, c should be limited to 7 decimal places by rounding the number upto the 7th decimal precision value.

Example #2

Code:

//package co.java.exception;
import java.math.BigDecimal;
public class ArithmeticException
{
public static void main(String[] args)
{
BigDecimal a=new BigDecimal(1);
BigDecimal b=new BigDecimal(6);
a=a.divide(b,7,BigDecimal.ROUND_DOWN);// limit of decimal place
System.out.println(a.toString());
}
}

Output:

BigDecimal Example 2

The output console shows the result as a number with a 7th decimal point value, which means rounding works fine.

How to Avoid or Handle Java ArithmeticException?

Handling the exception thrown by java virtual machine is known as exception handling. The advantage of exception handling is the execution of the code is not stopped.

An exception is handled by using a combination of try and catch. A try/catch block is placed in the code that might generate an exception. Code written inside a try/catch block is referred to as a protected code.

Syntax:

try
{
set of statements//protected code
}
catch (exceptionname except)
{
// Catch set of statements---can contain single catch or multiple.
}

ArithmeticException Handling using try & Catch Blocks

  • Write the statements that can throw ArithmeticException with try and catch blocks.
  • When an exception occurs, the execution falls to the catch block from an exception’s point of occurrence. It executes the catch block statement and continues with the statement present after the try and catch blocks. Below is the example:

Code:

public class ExceptionHandled
{
public static void main(String args[])
{
int x =100, y = 0;
int z;
System.out.println("Hello world");
try
{
z = x/y;
System.out.println(z);
}
catch(ArithmeticException except)
{
System.out.println("Avoid dividing by integer 0" + except );
}
System.out.println("Hello class");
System.out.println("Hello there");
}
}

Output:

try & Catch Blocks Example

Hello class and Hello, there are also printed on the output console apart from Hello world. This is the outcome of the exception handling mechanism.

Explanation:

  1. Try, and catchblocks are exception handling keywords in Java used completely used to handle the exception or unchecked error raised in the code without halting the execution of the code.
  2. Detect the trouble creating statements and place them in the try block. When the try block throws the exception, the catch block handles that exception, and the execution of the program goes further to the last statement.
  3. If the try block does not throw the exception, the catch block is simply overlooked.
  4. Run a suitable exception handler or statements in the catch block to handle or detect the exception thrown by the try block successfully.

Conclusion

This article has learned about java arithmetic exception and how to handle the exception under try and catch block. An arithmetic exception occurs most of the time because of the division of a number by integer 0. In this article, I have used a single catch for a single try, but we can also use multiple catch for a single try.

Recommended Articles

This is a guide to Java ArithmeticException. Here we discuss the Introduction and how to Avoid or Handle Java ArithmeticException along with examples. You can also go through our other suggested articles to learn more –

  1. JavaScript Math Functions
  2. Java Compilers
  3. Merge Sort In Java
  4. Optional Class in Java 8

Содержание

  1. Основные типы исключений (Exception) в java
  2. ArithmeticException
  3. ArrayIndexOutOfBoundsException
  4. ArrayStoreException
  5. ClassCastException
  6. ConcurrentModificationException
  7. EmptyStackException
  8. IllegalArgumentException
  9. IllegalMonitorStateException
  10. IllegalStateException
  11. IllegalThreadStateException
  12. IndexOutOfBoundsException
  13. MissingResourceException
  14. NegativeArraySizeException
  15. NoSuchElementException
  16. NullPointerException
  17. NumberFormatException
  18. SecurityException
  19. StringIndexOutOfBoundsException
  20. UndeclaredThrowableException
  21. UnsupportedOperationException
  22. Handling the ArithmeticException Runtime Exception in Java
  23. Introduction
  24. ArithmeticException & Why it is an Unchecked Exception
  25. How to Handle ArithmeticException
  26. ArithmeticException Examples
  27. Division by zero (integer arithmetic)
  28. Preferred approach
  29. Alternative approach
  30. Division by zero doesn’t always throw ArithmeticException
  31. Non-terminating decimal expansion (floating point arithmetic)
  32. Safe type casts & putting ArithmeticException to good use
  33. Conclusion
  34. Track, Analyze and Manage Errors With Rollbar

Основные типы исключений (Exception) в java

Перечень наиболее часто встречающихся исключений (исключительных ситуаций, ошибок) в языке программирования java с расшифровкой их значения.

ArithmeticException

Возникла исключительная ситуация, связанная с ошибкой при выполнении арифметического вычисления (например, с попыткой целочисленного деления на нуль). Класс ArithmeticalException унаследован от RuntimeException.

ArrayIndexOutOfBoundsException

Задано значение индекса массива, не принадлежащее допустимому диапазону. Имеется дополнительный конструктор, принимающий в качестве параметра ошибочное значение индекса и включающий его в текст описательного сообщения. Класс ArrayIndexOutOfBoundsException унаследован от IndexOutOfBoundException

ArrayStoreException

Предпринята попытка сохранения в массиве объекта недопустимого типа. Возникает, если попытаться записать в ячейку массива ссылку на объект неправильного типа.

Класс ArrayStoreException унаследован от RuntimeException.

ClassCastException

Выполнена неверная операция преобразования типов (ошибка приведения типов).

Класс ClassCastException унаследован от RuntimeException.

ConcurrentModificationException

Осуществлена попытка изменения объекта конкурирующим потоком вычислений (thread) с нарушением контракта класса (тип определен в пакете jav.util).

Также исключение может происходить при работе с коллекциями при обычной однопоточной работе. ConcurrentModificationException возникает когда коллекция модифицируется «одновременно» с проходом по коллекции итератором любыми средствами кроме самого итератора.

Класс ConcurrentModificationException унаследован от RuntimeException.

EmptyStackException

Возникает при попытке извлечения объекта из пустого стека. Тип обладает только конструктором без параметров, поскольку причина ситуации очевидна без дополнительных разъяснений (тип определен в пакете java.util).

Класс EmptyStackExceptionунаследован от RuntimeException.

IllegalArgumentException

Методу передано неверное значение аргумента (например, отрицательное, когда метод предполагает задание положительных значений).

Класс IllegalArgumentExceptionунаследован от RuntimeException.

IllegalMonitorStateException

Выполнено обращение к методу wait, notifyAll или notify объекта, когда текущий поток вычислений не обладает блокировкой (lock) этого объекта.

Класс IllegalMonitorStateException унаследован от RuntimeException.

IllegalStateException

Предпринята попытка выполнения операции в то время, когда объект не находится в соответствующем состоянии (например при регистрации или удалении ловушки события закрытия исполняющей системы (shutdown hook) после начала процедуры закрытия).

Класс IllegalStateExceptionунаследован от RuntimeException.

IllegalThreadStateException

Предпринята попытка выполнения операции в то время, когда объект потока вычислений не находится в соответствующем состоянии (например, вызван метод start для потока, который уже приступил к работе).

Класс IllegalThreadStateException унаследован от IllegalArgumentException

IndexOutOfBoundsException

Задано значение индекса массива или содержимого строки типа String, не принадлежащее допустимому диапазону.

Класс IndexOutOfBoundsException унаследован от RuntimeException

MissingResourceException

Не найден требуемый ресурс или пакет ресурсов (resource bundle). Единственный конструктор типа предусматривает задание трех аргументов: строки описательного сообщения, наименования класса ресурсов и объекта ключа, отвечающего отсутствующему ресурсу. Для получения строк наименования класса и ключа применяются методы detClassName и getKey соответственно (тип определен в пакете java.util).

Класс MissingResourceExceptionунаследован от RuntimeException.

NegativeArraySizeException

Предпринята попытка создания массива с размером, значение которого задано отрицательным числом.

Класс NegativeArraySizeException унаследован от RuntimeException.

NoSuchElementException

Операция поиска элемента в объекте одного из контейнерных классов завершилась неудачей (тип определен в пакете java.util).

Класс NoSuchElementException унаследован от RuntimeException.

NullPointerException

Возникает при попытке обращения к полю, методу или объекту по ссылке, равной null. Также исключение выбрасывается, когда метод, не допускающий передачи аргумента null, был вызван с заданием значения null. В последнем случае может быть сгенерировано и исключение типа IllegalArgumentException.

Класс NullPointerException унаследован от RuntimeException.

NumberFormatException

Строка, которая, как предполагалось должна содержать представление числа, не отвечает этому требованию. Исключение выбрасывается такими методами, как, например, Integer.parseInt.

Класс NumberFormatException унаследован от IllegalArgumentException.

SecurityException

Предпринята попытка выполнения операции, запрещенной системой обеспечения безопасности в соответствии с действующей политикой безопасности.

Класс SecurityException унаследован от RuntimeException.

StringIndexOutOfBoundsException

Задано значение индекса содержимого строки типа String, не принадлежащее допустимому диапазону. Имеется дополнительный конструктор, принимающий в качестве параметра ошибочное значение индекса и включающий его в текст описательного сообщения.

Класс StringIndexOutOfBoundsException унаследован от IndexOutOfBoundsException.

UndeclaredThrowableException

Выбрасывается при обращении к методу целевого объекта посредством объекта рефлективного класса Proxy, если метод invoke объекта InvocationHandler генерирует объявляемое исключение, которое не допускает присваивания ни одному из типов исключений, упомянутых в предложении throws метода целевого объекта. Рассматриваемое исключение содержит ссылку на исключение, генерируемое методом invoke, которое может быть получено с помощью метода getUndeclaredThrowable. Класс исключений UndeclaredThrowableException поддерживает два конструктора: оба принимают в качестве параметров ссылку на объект Throwable, а один из них, помимо того, строку описания (тип определен в пакете java.lang.reflect).

Класс UndeclaredThrowableException унаследован от RuntimeException.

UnsupportedOperationException

Предпринята попытка выполнения операции над объектом, который ее не поддерживает (например, модификация объекта, обозначенного признаком «только для чтения»). используется также классами коллекций из состава пакета java.util как реакция на вызов методов производного класса, реализация которых не обязательна.

Класс UnsupportedOperationException унаследован от RuntimeException.

Источник

Handling the ArithmeticException Runtime Exception in Java

Table of Contents

Introduction

Arithmetic is at the core of every program and every programming language in existence. From integer and floating-point arithmetic all the way down to bitwise and pointer arithmetic, these mathematical operations translate into machine instructions which execute with thundering speeds and manipulate the state of software applications used across all sorts of different domains. Most modern programming languages have a dedicated category of errors or exceptions for dealing with all the peculiar cases and problematic conditions that may arise while performing these arithmetic operations.

ArithmeticException & Why it is an Unchecked Exception

In Java, any arithmetic operation which creates an exceptional condition makes the Java Virtual Machine throw the ArithmeticException exception [1]. Generally speaking, anything that a scientific calculator isn’t able to process would throw this exception. At a lower level, certain rules and constraints are imposed by the programming language itself, so if any of these are broken, the ArithmeticException exception will emerge.

ArithmeticException inherits from the RuntimeException class which means it is an unchecked, runtime exception [2]. This is due to a language design decision made to reduce the exception handling clutter that would otherwise arise with the high frequency of arithmetic operations, but more importantly because throwing and propagating arithmetic exceptions wouldn’t make sense for the majority of cases, which in practice are the result of logical programming errors that need to be refactored, rather than exceptions that need to be handled. Consequently, Java doesn’t require ArithmeticException instances to be checked and will only let them manifest at runtime.

How to Handle ArithmeticException

To prevent the ArithmeticException exception in Java, one should diligently implement methods with arithmetic operations and ensure that they are correct from a mathematical and a semantical standpoint. If and when encountered, the ArithmeticException exception should instigate refactoring of the problematic code, and only in rare and justified cases, the exception should be explicitly handled.

ArithmeticException Examples

Division by zero (integer arithmetic)

Dividing a real number by zero is one of those mathematical operations that seem very simple but do not have a clean and definitive answer. The result of this operation is formally considered to be undefined, as any attempt at a definition leads to a contradiction [3]. Since this is a special case of the division operation, Java treats it as an exceptional condition and throws the ArithmeticException exception whenever it encounters it at runtime.

Preferred approach

The proper way to deal with division by zero is to make sure that the divisor variable is never zero, or when the input cannot be controlled and there is a possibility of zero manifesting itself in the equation, treating that as one of the expected options and resolving it accordingly. This usually means testing (validating) the value of the divisor before using it, as shown below:

Alternative approach

As with any other exception, it is possible to catch the ArithmeticException inside a try-catch construct, but this should generally be avoided as it creates memory overhead and understates the importance of validating input values and working with a bounded set of parameters.

Division by zero doesn’t always throw ArithmeticException

It is important to be aware that division by zero in the context of floating point numbers does NOT trigger the ArithmeticException . This is because the IEEE 754 standard [4] defines division by zero in floating point arithmetic as ±Infinity and the JVM specification follows this standard [5]. As it can be seen in the example below, setting the operand types to the double floating point number type, results in the positive Infinity constant [6] being assigned to the variable z , which then multiplied by itself yields Infinity again.

Non-terminating decimal expansion (floating point arithmetic)

Many Java software applications used in the financial sector or otherwise requiring the representation and manipulation of large numbers with great precision, rely on accurate floating point arithmetic and the use of specialized classes such as BigDecimal [7]. Working with these classes requires special attention to detail so as to avoid certain mistakes and prevent erroneous results. As an example, failing to specify a scale with a rounding mode to any operation that may produce a number with an infinite decimal expansion (such as 1.3333. ) [8] will throw an ArithmeticException .

The code in the example above declares two BigDecimal instances with the values of 1.8 and 9.2, and tries to divide the first one by the second one. However, since the result of 1.8/9.2 is 0.195652173913043478260869565217391304347826086…. with an endlessly repeating sequence, the BigDecimal::divide method is unable to return an exact value and the JVM throws an ArithmeticException . As the Java documentation for BigDecimal suggests:

“. In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3. If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations.”

The way out of this issue is to specify a scale of the quotient to be returned and a rounding policy to apply to the calculated result. One of the ways to do this is by invoking the overridden version of the BigDecimal::divide method which takes two additional parameters for scale and rounding mode, as demonstrated below. Now the resulting computation is a valid number rounded down to 4 decimal places, as explicitly specified.

Safe type casts & putting ArithmeticException to good use

In rare instances, particularly when designing libraries for use by other programs and APIs, ArithmeticException can effectively be used as a safeguard against undesired results and consequences. One such case is numeric type conversions (aka. casts), which Java allows to be done in either direction, from a smaller capacity type to a larger one and vice versa. Casting from a larger to a smaller capacity type is known as downcasting, which is a process where certain information may be lost if the value is larger than what the smaller type can hold. As a specific example, below is a small program casting the maximum value a long type can hold to an integer, i.e., int type. The resulting value here is -1 which is not representative of nor close to the initial value in any way.

To avoid this from happening, an explicit check can be performed to see whether the input value falls within the boundaries of what the target type can hold, as shown below.

This naive and straightforward approach will prevent unsafe casts by triggering the ArithmeticException exception, which is a reasonable solution in this scenario. A more succinct and idiomatic way of accomplishing the same would be to use the native Java method Math::toIntExact which essentially does the same under the hood and makes the type cast safe, i.e., checked.

Conclusion

Arithmetic operations are some of the most frequently encountered operations found in programming code. Java has a dedicated type of exception called ArithmeticException for dealing with exceptional conditions that arise from these operations. The key to preventing the ArithmeticException is being very explicit and deliberate in dealing with special cases such as integer division by zero and non-terminating decimal expansions in floating point arithmetic. Practical examples of these cases alongside possible ways and mechanisms for dealing with them are presented in this article. Finally, a software design scenario where the ArithmeticException exception can be used in a purposeful and beneficial manner is explored, in the context of safe numeric type conversions.

Track, Analyze and Manage Errors With Rollbar

Managing Java errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

Источник

What Is Arithmetic exception?

Thrown when an exceptional arithmetic condition has occurred. For example, an integer “divide by zero” throws an instance of this class.

In this tutorial, we will take a look at a few examples that will highlight the causes of getting an ArithmeticException in the Java program. Also, we will discuss the common causes of Arithmetic exception and how can we handle this exception.

An arithmetic exception is an error that is thrown when a “wrong” arithmetic situation occurs. This usually happens when mathematical or calculation errors occur within a program during run-time. There various causes to an ArithmeticException, the following are a few of them:

List of all invalid operations that throw an ArithmeticException() in Java

  • Dividing by an integer Zero
  • Non-terminating decimal numbers using BigDecimal

Dividing by an integer Zero:

Java throws an Arithmetic exception when a calculation attempt is done to divide by zero, where the zero is an integer. Take the following piece of code as an example:

package co.java.exception;
public class ArithmaticExceptionEx 
{
   void divide(int a,int b)
   {
      int q=a/b;
      System.out.println("Sucessfully Divided");
      System.out.println("The Value After Divide Is :-" +q);
   }
   public static void main(String[] args) 
   {
      ArithmaticExceptionEx obj=new ArithmaticExceptionEx();
      obj.divide(10, 0);
   }
}

When we run the code, we get the following error:

Exception in thread "main" java.lang.ArithmeticException: / by zero at co.java.exception.ArithmaticExceptionEx.divide(ArithmaticExceptionEx.java:7) at co.java.exception.ArithmaticExceptionEx.main(ArithmaticExceptionEx.java:14)

Since we divided 10 by 0, where 0 is an integer, java throws the above exception. However, if the zero is a floating-point as in the following code, we get a completely different result.

Here, no exception is thrown, and “Q” now has a value of infinity.  Note that is (almost) always a bad idea to divide by zero, even if no exception is thrown.

Non-terminating decimal numbers using BigDecimal:

The BigDecimal class is a Java class used to represent decimal numbers up to a very high number of precision digits. The class also offers a set of functionalities that are not available using primitive data types such as doubles and floats. These functionalities include rounding up/down, defining the number of decimal places we need from a number, etc.

Since BigDecimals are used to represent numbers to a high degree of accuracy, a problem might occur with some numbers, for example, when dividing 1 by 3, or 2 by 12. These numbers do not have a specific number of decimal places, for example, 1/3 = 0.33333333333333333…

Take the following program for example :

package co.java.exception;
import java.math.BigDecimal;
public class ArithmeticExceptionExamples {
   public static void main(String[] args) {
      // TODO Auto-generated method stub
      BigDecimal x = new BigDecimal(1);
        BigDecimal y = new BigDecimal(3);
        x = x.divide(y);       
        System.out.println(x.toString());
   }
}

Take a Look On The Execution:

In the program above, since the class doesn’t know what to do with the division result, an exception is thrown.

Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. at java.math.BigDecimal.divide(Unknown Source) at co.java.exception.ArithmeticExceptionExamples.main(ArithmeticExceptionExamples.java:11)

As we said, the program doesn’t know what to do with the result of the division, hence an exception is thrown with the message “Non-terminating decimal expansion”. One possible solution to the above problem is to define the number of decimal places we require from a big decimal, and the form of rounding that will be used to limit the value to a certain number of decimals. For example, we could  say that z should be limited to 7 decimal places, by rounding up at the 7th decimal place:

package co.java.exception;
import java.math.BigDecimal;
public class ArithmeticExceptionExamples {
   public static void main(String[] args) {
   // TODO Auto-generated method stub
   BigDecimal x = new BigDecimal(1);
        BigDecimal y = new BigDecimal(3);        
        x = x.divide(y, 7, BigDecimal.ROUND_DOWN);//here we limit the # of decimal places        
        System.out.println(x.toString());
   }
}

Here, the program runs properly, since we defined a limit to the number of places the variable “x”  could assume.

If You Have any doubts feel free to drop your doubts in the Comment Section.

Перечень наиболее часто встречающихся исключений (исключительных ситуаций, ошибок) в языке программирования java с расшифровкой их значения.

Содержание

  1. ArithmeticException 
  2. ArrayIndexOutOfBoundsException 
  3. ArrayStoreException 
  4. ClassCastException 
  5. ConcurrentModificationException 
  6. EmptyStackException
  7. IllegalArgumentException 
  8. IllegalMonitorStateException 
  9. IllegalStateException 
  10. IllegalThreadStateException 
  11. IndexOutOfBoundsException 
  12. MissingResourceException 
  13. NegativeArraySizeException 
  14. NoSuchElementException 
  15. NullPointerException 
  16. NumberFormatException
  17. SecurityException
  18. StringIndexOutOfBoundsException
  19. UndeclaredThrowableException
  20. UnsupportedOperationException 

ArithmeticException 

Возникла исключительная ситуация, связанная с ошибкой при выполнении арифметического вычисления (например, с попыткой целочисленного деления на нуль). Класс ArithmeticalException унаследован от RuntimeException.

ArrayIndexOutOfBoundsException 

Задано значение индекса массива, не принадлежащее допустимому диапазону. Имеется дополнительный конструктор, принимающий в качестве параметра ошибочное значение индекса и включающий его в текст описательного сообщения. Класс ArrayIndexOutOfBoundsException унаследован от IndexOutOfBoundException

ArrayStoreException 

Предпринята попытка сохранения в массиве объекта недопустимого типа. Возникает, если попытаться записать в ячейку массива ссылку на объект неправильного типа.

Класс ArrayStoreException унаследован от RuntimeException.

ClassCastException 

Выполнена неверная операция преобразования типов (ошибка приведения типов).

Класс ClassCastException унаследован от RuntimeException.

ConcurrentModificationException 

Осуществлена попытка изменения объекта конкурирующим потоком вычислений (thread) с нарушением контракта класса (тип определен в пакете jav.util).

Также исключение может происходить при работе с коллекциями при обычной однопоточной работе. ConcurrentModificationException возникает когда коллекция модифицируется «одновременно» с проходом по коллекции итератором любыми средствами кроме самого итератора.

Класс ConcurrentModificationException унаследован от RuntimeException.

EmptyStackException

Возникает при попытке извлечения объекта из пустого стека. Тип обладает только конструктором без параметров, поскольку причина ситуации очевидна без дополнительных разъяснений (тип определен в пакете java.util). 

Класс EmptyStackExceptionунаследован от RuntimeException.

IllegalArgumentException 

Методу передано неверное значение аргумента (например, отрицательное, когда метод предполагает задание положительных значений).

Класс IllegalArgumentExceptionунаследован от RuntimeException.

IllegalMonitorStateException 

Выполнено обращение к методу wait, notifyAll или notify объекта, когда текущий поток вычислений не обладает блокировкой (lock) этого объекта.

Класс IllegalMonitorStateException унаследован от RuntimeException.

IllegalStateException 

Предпринята попытка выполнения операции в то время, когда объект не находится в соответствующем состоянии (например при регистрации или удалении ловушки события закрытия исполняющей системы (shutdown hook) после начала процедуры закрытия).

Класс IllegalStateExceptionунаследован от RuntimeException.

IllegalThreadStateException 

Предпринята попытка выполнения операции в то время, когда объект потока вычислений не находится в соответствующем состоянии (например, вызван метод start для потока, который уже приступил к работе).

Класс IllegalThreadStateException унаследован от IllegalArgumentException

IndexOutOfBoundsException 

Задано значение индекса массива или содержимого строки типа String, не принадлежащее допустимому диапазону.

Класс IndexOutOfBoundsException унаследован от RuntimeException

MissingResourceException 

Не найден требуемый ресурс или пакет ресурсов (resource bundle). Единственный конструктор типа предусматривает задание трех аргументов: строки описательного сообщения, наименования класса ресурсов и объекта ключа, отвечающего отсутствующему ресурсу. Для получения строк наименования класса и ключа применяются методы detClassName и getKey соответственно (тип определен в пакете java.util).

Класс MissingResourceExceptionунаследован от RuntimeException.

NegativeArraySizeException 

Предпринята попытка создания массива с размером, значение которого задано отрицательным числом.

Класс NegativeArraySizeException унаследован от RuntimeException.

NoSuchElementException 

Операция поиска элемента в объекте одного из контейнерных классов завершилась неудачей (тип определен в пакете java.util).

Класс NoSuchElementException унаследован от RuntimeException.

NullPointerException 

Возникает при попытке обращения к полю, методу или объекту по ссылке, равной null. Также исключение выбрасывается, когда метод, не допускающий передачи аргумента null, был вызван с заданием значения null. В последнем случае может быть сгенерировано и исключение типа IllegalArgumentException.

Класс NullPointerException унаследован от RuntimeException.

NumberFormatException

Строка, которая, как предполагалось должна содержать представление числа, не отвечает этому требованию. Исключение выбрасывается такими методами, как, например, Integer.parseInt.

Класс NumberFormatException унаследован от IllegalArgumentException.

SecurityException

Предпринята попытка выполнения операции, запрещенной системой обеспечения безопасности в соответствии с действующей политикой безопасности.

Класс SecurityException унаследован от RuntimeException.

StringIndexOutOfBoundsException

Задано значение индекса содержимого строки типа String, не принадлежащее допустимому диапазону. Имеется дополнительный конструктор, принимающий в качестве параметра ошибочное значение индекса и включающий его в текст описательного сообщения.

Класс StringIndexOutOfBoundsException унаследован от IndexOutOfBoundsException.

UndeclaredThrowableException

Выбрасывается при обращении к методу целевого объекта посредством объекта рефлективного класса Proxy, если метод invoke объекта InvocationHandler генерирует объявляемое исключение, которое не допускает присваивания ни одному из типов исключений, упомянутых в предложении throws метода целевого объекта. Рассматриваемое исключение содержит ссылку на исключение, генерируемое методом invoke, которое может быть получено с помощью метода getUndeclaredThrowable. Класс исключений UndeclaredThrowableException поддерживает два конструктора: оба принимают в качестве параметров ссылку на объект Throwable, а один из них, помимо того, строку описания (тип определен в пакете java.lang.reflect).

Класс UndeclaredThrowableException унаследован от RuntimeException.

UnsupportedOperationException 

Предпринята попытка выполнения операции над объектом, который ее не поддерживает (например, модификация объекта, обозначенного признаком «только для чтения»). используется также классами коллекций из состава пакета java.util как реакция на вызов методов производного класса, реализация которых не обязательна.

Класс UnsupportedOperationException унаследован от RuntimeException.

Смотрите также: Методы обработки исключений в java

Понравилась статья? Поделить с друзьями:
  • Arithmetic error floating point overflow signalled
  • Ariston холодильник как изменить температуру
  • Ariston ошибка f07
  • Ariston ошибка e24
  • Ariston ошибка 5p3