VOOZH about

URL: https://www.geeksforgeeks.org/java/java-program-to-use-catch-to-handle-the-exception/

⇱ Java Program to use Catch to Handle the Exception - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Program to use Catch to Handle the Exception

Last Updated : 23 Jul, 2025

The exception is the event occurs when the program is executing. Due to this exception, the normal flow of the program will get disrupts. Whenever an exception occurs in the method, the method creates an object and sends that object to the runtime system. For example, the file needs to be open is not found, class not found exception, Arithmetic Exception, SQL Exception, etc.

To handle these exceptions there are 4 standard techniques: 

  • Try-catch
  • Throw
  • Throws
  • Using HandlerExceptionResolver interface (Only in Spring-framework)

Catch usage is described here below: 

Syntax:

try {

 // Put the code in the try block which may occur any
 // kind of exception
}
catch (ExceptionName e) {

 
 // handle the exception
}

There are two examples discussed below:

  1. Using predefined exception Class
  2. Using defining own exception Class

Example 1: Usage of catch with a predefined exception class

This is an example of a predefined exception which is handled by try and catch block.

Output:

👁 Image


 Example 2: Usage of catch by defining the exception class 

In this example, the exception is user-defined in which exception class is written as follows:

Input 1:
Enter the name : Geek
Enter the age: 18

Output: 
Age must be greater than 18 // Age is equal to 18 so the exception is occurred

Input 2:
Enter the name : Geek
Enter the age: 20

Output:
name: Geek
age:20 // Age is greater than 18 so no exception.
Comment