Q:

Java program to handle a generated exception

belongs to collection: Java Exception Handling Programs

0

Java program to handle a generated 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 exception (run-time error) using trycatch 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 a generated exception is given below. The given program is compiled and executed successfully.

// Java program to handle a generated exception

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

      c = a / b;

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

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

Output:

Exception generated
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, divide by zero exception gets generated but we handled exception using the "catch" block and prevent from the program crashing.

 

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

total answers (1)

Java program to handle Null Pointer Exception... >>