We can create a custom exception handling in java. For that, we have to inherit the Exception class of java library. Here we explain some program which describes the custom Exception. We must display a valid statement for the exception. For that, we create a Class which extends Exception class.
class AgeBelow0 extends Exception
{
private int age;
AgeBelow0(int a)
{
age = a;
}
public String toString()
{
return "Age can Not Be " + age;
}
}
class TestAgeBelow0
{
static void age(int a) throws AgeBelow0
{
System.out.println("Called age(" + a + ")");
if(a < 0)
throw new AgeBelow0(a);
System.out.println("Normal exit");
}
public static void main(String args[])
{
try
{
age(10);
age(-20);
age(20);
}
catch (AgeBelow0 e)
{
System.out.println("Caught " + e.toString());
}
}
}
Output:
Called age(10)
Normal exit
Called age(-20)
Caught Age can Not Be -20