×

Java Programs

Java Practice

Java program to handle a generated exception

Java example to handle a generated exception.
Submitted by Nidhi, on April 17, 2022

Problem statement

In this program, we will handle an exception (run-time error) using 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.

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.

Java Exception Handling Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.