Java program to throw an exception explicitly

Java example to throw an exception explicitly.
Submitted by Nidhi, on April 20, 2022

Problem Solution:

In this program, we will throw an exception explicitly using the "throw" keyword in the "try" block. Then we will catch the exception.

Program/Source Code:

The source code to throw an exception explicitly is given below. The given program is compiled and executed successfully.

// Java program to throw an exception explicitly

public class Main {
  public static void main(String[] args) {
    try {
      throw new Exception("Throwing an exception.");
    } catch (Exception e) {
      System.out.println("Exception: " + e);
    } finally {
      System.out.println("The finally block executed");
    }

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

Output:

Exception: java.lang.Exception: Throwing an exception.
The finally block executed
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, catch, and finally blocks. In the try block, we throw an exception explicitly using the throw keyword which is handled in the catch block and printed appropriate message.

Java Exception Handling Programs »






Comments and Discussions!

Load comments ↻






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