Home »
Java »
Java Programs
Java program to throw an exception explicitly
Java example to throw an exception explicitly.
Submitted by Nidhi, on April 20, 2022
Problem statement
In this program, we will throw an exception explicitly using the "throw" keyword in the "try" block. Then we will catch the exception.
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 »