Arithmetic exception: division by zero error

Any number divided by zero gives the answer “equal to infinity.” Unfortunately, no data structure in the world of programming can store an infinite amount of data. Hence, if any number is divided by zero, we get the arithmetic exception.

How can we solve it?

Exceptions are not errors; they are run-time issues that may or may not occur. Java enables us to handle exceptions by providing the try catch block.

The try block has the potential code that may generate an exception, while the catch block has the message that should be generated when the exception occurs.

Code

The following code generates an​ arithmetic exception.

class example {
public static void main (String args[]) {
int num1 = 15, num2 = 0, result = 0;
try{
result = num1/num2;
System.out.println("The result is" +result);
}
catch (ArithmeticException e) {
System.out.println ("Can't be divided by Zero " + e);
}
}
}
Copyright ©2024 Educative, Inc. All rights reserved