Java enables a programmer to create their own exception by extending Exception class and its subclasses. You can make two types of custom exceptions-
class InvalidMonthException extends Exception { public InvalidMonthException(String message) { super(message); } }
class Test { public static void monthValidity(int month) throws InvalidMonthException { if(month<1 || month>12) { throw new InvalidMonthException("Invalid Month"); } else { System.out.println("Entered correct month."); } } public static void main(String args[]) { try { monthValidity(14); } catch(InvalidMonthException e) { System.out.println("Exception arised "+e); } } }
Output
Exception arised InvalidMonthException: Invalid Month