Though Java provides an extensive set of in-built exceptions, there are cases in which we may need to define our own exceptions in order to handle the various application specific errors that we might encounter.
While defining an user defined exception, we need to take care of the following aspects:
- The user defined exception class should extend from Exception class.
- The toString() method should be overridden in the user defined exception class in order to display meaningful information about the exception.
Let us see a simple example to learn how to define and make use of user defined exceptions.
NegativeAgeException.java
1 2 3 4 5 6 7 8 9 10 11 12 | public class NegativeAgeException extends Exception {
private int age;
public NegativeAgeException(int age){
this.age = age;
}
public String toString(){
return "Age cannot be negative" + " " +age ;
}
} |
CustomExceptionTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class CustomExceptionTest {
public static void main(String[] args) throws Exception{
int age = getAge();
if (age < 0){
throw new NegativeAgeException(age);
}else{
System.out.println("Age entered is " + age);
}
}
static int getAge(){
return -10;
}
}</code> |
In the CustomExceptionTest class, the age is expected to be a positive number. It would throw the user defined exception NegativeAgeException if the age is assigned a negative number.
At runtime, we get the following exception since the age is a negative number.
1 2 | Exception in thread "main" Age cannot be negative -10 at tips.basics.exception.CustomExceptionTest.main(CustomExceptionTest.java:10) |






October 9, 2007
Java