Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Wednesday, April 2, 2025

Java program to implement user defined exception handling

Objective:  Write a Java program to implement user defined exception handling.


Code:


// Custom Exception class

class InvalidAgeException extends Exception {

    public InvalidAgeException(String message) {

        super(message);

    }

}


// Main class to demonstrate user-defined exception handling

public class UserDefinedExceptionDemo {

    

    // Method to check age eligibility

    static void checkAge(int age) throws InvalidAgeException {

        if (age < 18) {

            throw new InvalidAgeException("Age must be 18 or above to vote.");

        } else {

            System.out.println("You are eligible to vote.");

        }

    }

    public static void main(String[] args) {

        try {

            checkAge(16);  // Example with an invalid age

        } catch (InvalidAgeException e) {

            System.out.println("Exception caught: " + e.getMessage());

        }

    }

}



Output: 




No comments:

Post a Comment