×

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are defined in the Java programming language. In this part, we will look at one of Java's most well-known exceptions, the Arithmetic Exception.

An arithmetic exception is an unexpected result or unchecked error in the code that is thrown or raised anytime a faulty mathematical or arithmetic operation emerges in the code during run time.

Exception.java

public class Exception {
   public static void main(String[] args) {
      int a = 0, b = 10;
      int C;
      System.out.println("Value of C is : "+ b/a);
   }
}

Output:

Arithmetic exception in Java

A runtime problem, also known as an exception, occurs when the fraction's denominator is zero, and the JVM cannot determine the result; as a consequence, the program execution is halted, and an exception is reported. It should be noted that the program quits at the point when the exception is triggered. However, the preceding code is performed, and the proper result is printed.

A Java Arithmetic Exception is a type of unchecked error or unexpected result of code that is produced when incorrect arithmetic or mathematical operation occurs in code at run time. When the denominator is integer 0, the JVM is unable to evaluate the result, so the program's execution is halted, and an exception is produced. The program quits at the place where the exception is thrown, but the code preceding that is performed, and the result is shown.

To avoid the ArithmeticException exception in Java, implement arithmetic operations with care and guarantee that they are correct both mathematically and semantically. When found, the Arithmetic Exception error should trigger refactoring of the problematic code, and the exception should be explicitly handled only in rare and warranted circumstances.

Handling Arithmetic Exceptions:

  • Try and catch blocks should be used to surround statements that potentially throw ArithmeticException.
  • The ArithmeticException can be caught.
  • As the execution does not abort, take the essential action for our code.

Exception.java

import java.io.*;
import java.lang.*;
class Exception
{
static int x = 5, y = 0, z;
static int div ()
{
try
{
if (y == 0)  // throws an exception
{
throw new ArithmeticException ( " DIVISION BY ZERO ");  // throws an exception explicitly
} // if
else
{
return ( x / y );
} // else
} // try
catch (ArithmeticException ae)
{
System.out.println ("ArithmeticException caught at div ( ) ");
throw ae;  // rethrows an exception
} // catch
} // div
public static void main (String args [ ] ) throws IOException
{
try
{
int w = div ();
System.out.println (" w = " + w);
try
{
String s1= null;
System.out.println (s1.length ( ) );  // NullPointerException
String s2 = " abc ";
int i = Integer.parseInt (s2);  // NumberFormatException
System.out.println (i);
int a [ ]=new int [5];
a [10] = 50;  // ArrayIndexOutOfBoundsException
} // inner-try
catch (NullPointerException npe)
{
System.out.println (" NullPointerException at main () = " + npe);
} // catch
catch (NumberFormatException nfe)
{
System.out.println (" NumberFormatException at main () = " + nfe);
}// catch
catch (ArrayIndexOutOfBoundsException aie)
{
System.out.println ("ArrayIndexOutOfBoundsException at main ( ) = " + aie);
} // catch
} // outer-try
catch (ArithmeticException ae)
{
System.out.println (" Exception Recaught at main ( ) = " + ae);
} // catch


finally
{
System.out.println (" CLOSING THE Exception Handling PROGRAM ");
} // finally
} // main
} // ExceptionHandling

Output:

Arithmetic exception in Java

Related Topics

Switch Case Program in Java

Switch Case Program in Java The switch case program in Java controls which code snippet gets executed on the basis of the value of the expression mentioned in the switch statement....

22 minutes read.

Literals in Java

In this article we acknowledge ourselves about the term literals in java, types of literals and an example to each of them. Literal Literal refers to any constant value that can be...

4 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

How to add 24 Hours to Date in Java?

In this tutorial, we will learn how to add 24 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

Difference between Abstract Class and Interface

There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s...

2 minutes read.

Java Math subtractExact() Method

The subtractExact() method of Java Math class returns mathematical difference of the specified two arguments, throwing an exception if the result overflows int or long. Syntax: public static int subtractExact (int x,...

1 minute read.

How to add 4 Years to the Current Date in Java?

In this tutorial, we will learn how to add 4 years to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Matrix Multiplication in Java

In Java, using the binary operator (*) we can perform matrix multiplication. A Matrix is a group of arrays. In the multiplication of matrices, the elements of each row are...

3 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.

How to Iterate List in Java?

List is a Collection foundation interface in Java. It enables us to keep the collection of objects in order. The four classes that make up the List interface implementation are...

3 minutes read.

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

Java Garbage Collection Interview Questions

One of the key areas of Java is garbage collection. Garbage collection enables apps to manage memory automatically. Interviewers frequently ask inquiries about garbage collection. Q1: What is the purpose of...

6 minutes read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.

Java Instanceof Keyword

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). The type of comparison in java differentiates the...

4 minutes read.

Duodecimal in Java

Duodecimal is a notation style in which a number with a base of 12 is referred to be a duodecimal number. In Java, we can use to convert duodecimal integers...

2 minutes read.