Custom Exception in Java

Java enables a programmer to create their own exception by extending Exception class and its subclasses. You can make two types of custom exceptions-

  1. Custom Checked Exception- You create a custom checked exception, all you need to do is subclass Exception or any of its subclasses (leave subclasses of RuntimeException class).
  2. Custom Unchecked Exception- To create a custom unchecked exception, all you need to do is subclass RuntimeException or any of its subclasses.

Example of custom exception

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