Java Custom Exception
Chapter:
Exception Handling
Last Updated:
25-03-2017 05:53:50 UTC
Program:
/* ............... START ............... */
public class InvalidAgeException extends Exception
{
InvalidAgeException(String msg)
{
super(msg);
}
}
public class JavaCustomException {
static void validate(int age) throws InvalidAgeException
{
if (age < 18)
{
throw new InvalidAgeException("Age not valid.");
}
else
{
System.out.println("You are welcome to vote.");
}
}
public static void main(String[] args)
{
try
{
validate(16);
}
catch (Exception e)
{
System.out.println("Exception occured : " + e);
}
System.out.println("Rest of code...");
}
}
/* ............... END ............... */
Output
Exception occured : InvalidAgeException: Age not valid.
Rest of code...
Notes:
-
If you are creating your own Exception that is known as custom exception or user-defined exception. Java custom exceptions are used to customize the exception according to user need.
Tags
Custom Exception, Exception, Java