Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
divisor
exception
catch
communitycreator

How to catch an exception caused by 0 as a divisor in Java

okwudili onyejiaku

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 value
      int numValue = 100;

      // divide by 0 and print value
      System.out.println(numValue/0);
    }
}
ArithmeticException error is thrown when a number value is divided by 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 value
        int numValue = 100;

        // divide by 0 and print value
        System.out.println(numValue/0);
      }      
      catch(ArithmeticException e)
      {
        System.out.println("The error is :" +  e);
      }
    }
}
Catch exception caused by dividing a number by 0 in Java

Explanation 2

In the code above:

  • Line 3: We use the try/catch exception 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.

RELATED TAGS

java
divisor
exception
catch
communitycreator
RELATED COURSES

View all Courses

Keep Exploring