Arithmetic exception java пример

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.

Читайте также:  What is skip list in java

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

Источник

Arithmetic Exception in Java

Java Course - Mastering the Fundamentals

Exception handling is a mechanism in java to handle unwanted interruptions like exceptions and continue with the normal flow of the program. Java uses try-catch blocks and other keywords like finally, throw, and throws to handle exceptions.

Arithmetic exceptions are raised by JVM when we try to perform any arithmetic operation which is not possible in mathematics. One of the most common arithmetic exceptions that occur is when we divide any number with zero.

What is an Arithmetic Exception in Java?

An arithmetic exception in java is a Runtime exception present in the java.lang package. JVM throws Arithmetic Exception when a wrong mathematical expression occurs in a java program. The base class of java arithmetic exception is java.lang.ArithmeticException which comes under java.lang.RuntimeException .

Exception Hierarchy

JVM throws Arithmetic exceptions in the following two scenarios:

  1. Division of a Number by an integer 0 — An arithmetic exception in java is thrown when we try to divide any number by 0.

Example: 198/0

  1. Division of Non-terminating long decimal numbers by Big Decimal — An arithmetic exception in java is thrown when we try to divide a big decimal number by any big decimal number.

Example: 75.908976756456/2.987865675

Structure of ArithmeticException in Java

Aritmetic Exception Hierarchy

ArithmeticExeption in java is present in java.lang package. Let’s see the hierarchy of this exception in Java.

Arithmetic Exception Constructor

Constructors in java is a special method with the name same as the class name. The arithmetic Exception class has two constructors used to throw exceptions according to the requirements. There are two types of Constructors in ArithmeticException Class in Java.

1. ArithmeticException() : Defines an ArithmeticException with no parameter passed or without any detailed message.

2. ArithmeticException(String s) : Defines an ArithmeticException with one parameter passed. The parameter String s is the detailed message which explains why the ArithmeticException occurred.

When an Arithmetic Exception Occurs in Java?

Arithmetic exception in Java occurs in two cases:

1. Division by 0 JVM throws an arithmetic exception when any number is divided by 0. This exception is thrown as a / by zero exception. Let’s see the same using an example.

In this example, division method is defined to perform division. The object of class ArithmeticExceptionDemo is created and the method is called using the same object. Here the parameters passed to the division method are 180 and 0 . Here we are trying to perform division 180/0 which is not possible mathematically hence the JVM throws the ArithmeticException .

2. Division of Non-Terminating Big Decimal JVM throws an arithmetic exception when a big-decimal i.e non terminating decimal number is divided by another big-decimal number. This exception is thrown as a Non-terminating decimal expansion; no exact representable decimal result. exception. Let’s see the same using an example.

Читайте также:  Deep learning with python by francois chollet

In this example, two big decimal numbers a1,a2 are declared. Here we are trying to divide a1 by a2 and store the result in a1. But the division of big decimal numbers results in a non-terminating decimal number. It is not possible to display the result hence JVM throws the ArithmeticException as displayed in the output section.

How to Handle Arithmetic Exceptions in Java?

In java customized exception handling is achieved using five keywords: try, catch, throw, throws, and finally. Here is how these keywords work in short.

  • Try block contains the program statements that may raise an exception.
  • Catch block catches the raised exception and handles it.
  • Throw keyword is used to explicitly throw an exception.
  • Throws keyword is used to declare an exception.
  • Finally block contains statements that must be executed after the try block.

We can handle arithmetic exceptions in java in the try-catch block. Try block will contain doubtful statements that can throw arithmetic exceptions while catch block is used to handle the exception and display an appropriate message.

Let’s see how to handle arithmetic exceptions in java using examples in the next exception.

Arithmetic Exception in Java Examples

  • Example 1: In this example, we will see how to handle ArithmeticException thrown by 0 division error using try-catch block in java.

In this example, the division of two bigdecimal numbers is performed in the try block, and the ArithmeticException thrown due to this is handled in the catch block. The catch block displays the exception thrown as the output and the flow of the program continues after it.

  • Example 2: In this example, we will see how to handle ArithmeticException thrown by a Non-terminating big decimal division error using the try-catch block in java.

In this example, division of two bigdecimal numbers is performed in try block and the ArithmeticException thrown due to this is handled in catch block. The catch block displays the execption thrown as the output and the flow of program continues after it.

Conclusion

  • JVM throws ArithmeticException when we try to perform any operation that is not possible mathematically.
  • ArithmeticException is present in java.lang package and extends java.lang.RuntimeException class in java.
  • ArithmeticException occurs in two cases: Division of any number by 0 and Divison of non-terminating big-decimal number.
  • Try-catch block is used to handle arithmetic exceptions in java.

Источник

Java Exception Handling Examples

In this tutorial, we will see examples of some of the popular exceptions and how to handle them properly using try-catch block. We will see exception handling of ArithmeticException, ArrayIndexOutOfBoundsException, NumberFormatException, StringIndexOutOfBoundsException and NullPointerException.

If you are new to the concept of exception handling, I highly recommend you to refer this starter guide: Exception handling in Java.

Читайте также:  Условия в форме html

Example 1: Arithmetic exception

This exception occurs when the result of a division operation is undefined. When a number is divided by zero, the result is undefined and that is when this exception occurs.

class JavaExample < public static void main(String args[]) < try< int num1=30, num2=0; int output=num1/num2; System.out.println ("Result: "+output); >catch(ArithmeticException e) < System.out.println ("You Shouldn't divide a number by zero"); >> >

Output of above program:

You Shouldn't divide a number by zero

Example 2: ArrayIndexOutOfBounds Exception

This exception occurs when you try to access an array index that doesn’t exist. For example, If array is having only 5 elements and you are trying to display 7th element then it would throw this exception.

class JavaExample < public static void main(String args[]) < try< int a[]=new int[10]; // This will throw exception as Array has // only 10 elements and we are trying to access // 12th element. a[11] = 9; >catch(ArrayIndexOutOfBoundsException e) < System.out.println ("ArrayIndexOutOfBounds Exception occurred"); System.out.println ("System Message: "+e); >> >

Exception output

In the above example the array is initialized to store only 10 elements indexes 0 to 9. Since we are trying to access element of index 11, the program is throwing this exception.

Example 3: NumberFormat Exception

This exception occurs when a string is parsed to any numeric variable.
For example, the statement int num=Integer.parseInt («XYZ»); would throw NumberFormatException because String “XYZ” cannot be parsed to int.

class JavaExample < public static void main(String args[]) < try< int num=Integer.parseInt ("XYZ") ; System.out.println(num); >catch(NumberFormatException e) < System.out.println("Number format exception occurred"); >> >
Number format exception occurred

Example 4: StringIndexOutOfBound Exception

  • A string is nothing but an array of string type. This exception occurs when you try to access an index that doesn’t exist, similar to what we have seen in ArrayIndexOutOfBoundsException.
  • Each character of a string object is stored in a particular index starting from 0. For example: In the string “beginnersbook”, the char ‘b’ is stored at index 0, char ‘e’ at index 1 and so on.
  • To get a character present in a particular index of a string we can use a method charAt(int) of java.lang.String where int argument is the index.

In the following example, the scope of the string “beginnersbook” is from index 0 to 12, however we are trying to access the char at index 40, which doesn’t exist, hence the exception occurred.

class JavaExample < public static void main(String args[]) < try< String str="beginnersbook"; System.out.println(str.length()); char c = str.charAt(40); System.out.println(c); >catch(StringIndexOutOfBoundsException e) < System.out.println("StringIndexOutOfBoundsException."); >> >
13 StringIndexOutOfBoundsException.

Exception occurred because the referenced index was not present in the String.

Example 5: NullPointer Exception

Class: Java.lang.NullPointer Exception
This exception occurs when you are trying to perform some operation on an object that references to the null value.

class JavaExample < public static void main(String args[]) < try< String str=null; System.out.println (str.length()); >catch(NullPointerException e) < System.out.println("NullPointerException.."); >> >

Here, length() is the function, which should be used on an object. However in the above example String object str is null so it is not an object due to which NullPointerException occurred.

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

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