Aim:
To implement the user defined exception concept in java
Algorithm:
- Create a user-defined exception class called MyException
- Throw an exception of user-defined type as an argument in main()
- The exception is handled using try, catch block
- 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