Custom Exception Handling in Java
softetechnologies
13-09-2017    1340 times
Custom Exception Handling

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.

Write a program using java that handles an exception "Entry of negative age of a person". [WBUT MCA 2014]

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());
}
}
}

Private Teacher

Output:

Called age(10)
Normal exit
Called age(-20)
Caught Age can Not Be -20

softetechnologies
softetechnologies
    Author Details
Arnab De
I have over 16 years of experience working as an IT professional, ranging from teaching at my own institute to being a computer faculty at different leading institute across Kolkata. I also work as a web developer and designer, having worked for renowned companies and brand. Through tutorialathome, I wish to share my years of knowledge with the readers.
    Related Post
  Query About the post