Java Program to Implement the User Defined Exception Concept

Aim:

To implement the user defined exception concept in java

Algorithm:

  1. Create a user-defined exception class called MyException
  2. Throw an exception of user-defined type as an argument in main()
  3. The exception is handled using try, catch block
  4. Display the user-defined exception

Program:

class InvalidAgeException extends Exception{  
InvalidAgeException(String s){  
super(s);  
}  
}
public class Main{  
public static void main(String args[]){  
try{  
validate(13);  
}catch(Exception m){System.out.println("Exception occured: "+m);}  
}  
static void validate(int age)throws InvalidAgeException{  
if(age<18)  
throw new InvalidAgeException("not valid");  
else  
System.out.println("welcome to vote");  
}  
}

Execution:

Exception occurred : Invalid Age Exception : not valid

Leave a Comment