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");


Exception: java.lang.Exception: Throwing an exception.
The finally block executed
Program Finished


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!


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.