Q:

Java program to throw an exception explicitly

belongs to collection: Java Exception Handling Programs

0

Java program to throw an exception explicitly

All Answers

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

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 trycatch, 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.

 

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

total answers (1)

Java program to demonstrate the throws keyword... >>
<< Java program to implement finally block when an ex...