Java Exception Handling

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

Program 1

class UnderAgeException extends Exception 
{
    public UnderAgeException(String message)
 {
        super(message);
    }
}

public class TestException1
 {

    public static void validateAge(int age) throws UnderAgeException 
{
        if (age < 5) {
            throw new UnderAgeException("Age must be 5 or above to join the Kathak course.");
        }
        System.out.println("Admission successful!");
    }

    public static void main(String[] args) 
{
        try {
            validateAge(9);
        } 
         catch (UnderAgeException e) 
        {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }
}
        //  throw new UAE("by five")

Program 2

class UnderAgeException extends Exception 
{
    public UnderAgeException(String message)
 {
        super(message);
    }
}

public class TestException
 {

    public static void validateAge(int age) throws UnderAgeException 
{
        if (age < 5) {
            throw new UnderAgeException("Age must be 5 or above to join the Kathak course.");
        }
        System.out.println("Admission successful!");
    }

    public static void main(String[] args) 
{
         {
            validateAge(3);
        }
         catch (UnderAgeException e) 
        {
           System.out.println("Exception caught: " + e.getMessage());
        }
    }
}

 

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *