Arithmetic exceptions in java

How to handle the ArithmeticException (unchecked) in Java?

The java.lang.ArithmeticException is an unchecked exception in Java. Usually, one would come across java.lang.ArithmeticException: / by zero which occurs when an attempt is made to divide two numbers and the number in the denominator is zero. ArithmeticException objects may be constructed by the JVM.

Example1

public class ArithmeticExceptionTest < public static void main(String[] args) < int a = 0, b = 10; int c = b/a; System.out.println("Value of c is : "+ c); >>

In the above example, ArithmeticExeption is occurred due to denominator value is zero.

  • java.lang.ArithmeticException: Exception thrown by java during division.
  • / by zero: is the detail message given to ArithmeticException class while creating the ArithmeticExceptionobject.

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:5)

How to handle ArithmeticException

Let us handle the ArithmeticException using try and catch blocks.

  • Surround the statements that can throw ArithmeticException with try and catch blocks.
  • We can Catch the ArithmeticException
  • Take necessary action for our program, as the execution doesn’tabort.

Example2

public class ArithmeticExceptionTest < public static void main(String[] args) < int a = 0, b = 10 ; int c = 0; try < c = b/a; >catch (ArithmeticException e) < e.printStackTrace(); System.out.println("We are just printing the stack trace.\n"+ "ArithmeticException is handled. But take care of the variable \"c\""); >System.out.println("Value of c :"+ c); > >

When an exception occurs, the execution falls to the catch block from the point of occurrence of an exception. It executes the statement in the catch block and continues with the statement present after the try and catch blocks.

Читайте также:  Биты в строку питон

Output

We are just printing the stack trace. ArithmeticException is handled. But take care of the variable "c" Value of c is : 0 java.lang.ArithmeticException: / by zero at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:6)

Источник

What Is Arithmetic exception In Java – Class java.lang. ArithmeticException

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:

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 ArithmeticException

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.

Web development, programming languages, Software testing & others

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
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); >>

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
//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); >>

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
//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()); >>

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 7 th decimal precision value.

Example #2
//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()); >>

The output console shows the result as a number with a 7 th 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.

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:
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"); > >

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.

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 –

89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

JAVA Course Bundle — 78 Courses in 1 | 15 Mock Tests
416+ Hours of HD Videos
78 Courses
15 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.8

Источник

Оцените статью