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.
try{numbervaleu / 0; // number value divide by 0}catch (ArithmeticException e) // catch the error{System.out.println(e)}
class HelloWorld {public static void main( String args[] ) {// create a number valueint numValue = 100;// divide by 0 and print valueSystem.out.println(numValue/0);}}
In the code above:
The code above throws an error. Let's handle this error below:
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);}}}
In the code above:
try/catch
exception handling to catch the error.ArithmeticException
.