×

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

How to achieve Multiple Inheritance in Java

Multiple Inheritance is the type of inheritance where one class inherits the properties of more than one super class. For example, class Child inherits (extends) the classes Father and Mother....

4 minutes read.

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

Java Math signum() Method

The signum() method of Java Math class returns the signum function of the value. Syntax: public static double signum(double d)public static float signum (float d) Parameters: The parameter ‘d’ represents the floating-point value whose...

2 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

Intersection Point of two linked list in Java

In this article, you will be very well acknowledged about how to achieve the intersection point of two linked list in Java. There are several approaches to obtain. Surely each...

8 minutes read.

Java Public Keyword

A Java access modifier is a public keyword. It can be applied to classes, constructors, methods, and variables. It is the type of access modifier that is least constrained. A...

4 minutes read.

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

Java Numbers

We use primitive data types like byte, int, long, double, etc to work with the numbers, When we need objects, we use wrapper class like Integer, Double, Long, Byte, etc....

2 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

How to Calculate Week Number From Current Date in Java?

The WeekFields class's weekOfMonth() method is utilized to return the field for access the week of a month based on this WeekFields. If the first day of the month is a...

3 minutes read.

Java Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

2 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

3 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.