Q:

Java program to handle Arithmetic Exception

belongs to collection: Java Exception Handling Programs

0

Java program to handle Arithmetic Exception

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will handle an Arithmetic Exception using the try, catch block. The code that may generate an exception should be written in the "try" block, and the "catch" block is used to handle the exception and prevent program crashes.

Program/Source Code:

The source code to handle Arithmetic Exceptions is given below. The given program is compiled and executed successfully.

// Java program to handle Arithmetic Exception

public class Main {
  public static void main(String[] args) {
    try {
      int a = 10;
      int b = 0;
      int c = 0;

      c = a / b;

      System.out.println("Division is: " + c);
    } catch (ArithmeticException e) {
      System.out.println("Exception: " + e);
    }

    System.out.println("Program Finished");
  }
}

Output:

Exception: java.lang.ArithmeticException: / by zero
Program Finished

Explanation:

In the above program, we created a class Main. The Main class contains a main() method. The main() method is the entry point for the program. Here, we created "try" and "catch" blocks. In the "try" block, the Arithmetic exception gets generated because we divided an integer number by zero.

Here, we handled generated exceptions using the "catch" block and printed exception message.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to handle ClassNotFoundException... >>
<< Java program to handle ArrayIndexOutOfBoundsExcept...