How to catch an exception caused by 0 as a divisor in Java
Overview
We can use the try/catch exception handling to catch the exception if a divisor is 0 in Java. When a particular number value is divided by 0, an exception called ArithmeticException is thrown.
Syntax
try{numbervaleu / 0; // number value divide by 0}catch (ArithmeticException e) // catch the error{System.out.println(e)}
Syntax for try/catch for ArithmeticException error
Example 1
class HelloWorld {public static void main( String args[] ) {// create a number valueint numValue = 100;// divide by 0 and print valueSystem.out.println(numValue/0);}}
Explanation 1
In the code above:
- Line 5: We create a number value.
- Line 8: We divide the number value by 0 and print the result.
The code above throws an error. Let's handle this error below:
Example 2
class HelloWorld {public static void main( String args[] ) {try{// create a number valueint numValue = 100;// divide by 0 and print valueSystem.out.println(numValue/0);}catch(ArithmeticException e){System.out.println("The error is :" + e);}}}
Explanation 2
In the code above:
- Line 3: We use the
try/catchexception handling to catch the error. - Line 10: We specify that the error to catch is any error or exception called
ArithmeticException. - Line 12: We print the error to the console.