How to Create User Defined Exception in Java?
In this tutorial we will discuss about how to create User Defined Exception in Java. Since already Java contains all pre-defined Exceptions and why we need to create User Defined Exceptions in our Application?
To Handle our application specific Exceptions can be placed under User Defined Exception.
To create our own Exception class we need to extend Exception class in our class. By this all base class (Throwable) methods will be extended to our Exception class.
Methods from Throwable class are
String toString()
String getMessage()
void printStackTrace()
String getLocalizedMessage()
Throwable fillInStackTrace()
void printStackTrace(PrintStream stream)
For example in our online portal application users age should not be less than 18 and should not be greater than 35. So as per their age we need to allow users to access the application. So here we can create our own Exception to handle the users age from 18 to 35. If users age not matches the condition then we need throw a Exception.
Lets see small example Java code as how to write User Defined Exception in Java.
OUTPUT:
By above way we can define our own Exceptions for our application needs.
To Handle our application specific Exceptions can be placed under User Defined Exception.
To create our own Exception class we need to extend Exception class in our class. By this all base class (Throwable) methods will be extended to our Exception class.
Methods from Throwable class are
String toString()
String getMessage()
void printStackTrace()
String getLocalizedMessage()
Throwable fillInStackTrace()
void printStackTrace(PrintStream stream)
For example in our online portal application users age should not be less than 18 and should not be greater than 35. So as per their age we need to allow users to access the application. So here we can create our own Exception to handle the users age from 18 to 35. If users age not matches the condition then we need throw a Exception.
Lets see small example Java code as how to write User Defined Exception in Java.
public class MyException extends Exception{
public MyException(){
super();
}
public MyException(String expSrt){
super(expSrt);
}
public String toString(){
return "Exception: Age should be 18 to 35 years only";
}
}
public class MyApplication {
public static void main(String[] args) {
int age = 15;
try{
if(age < 18 || age > 35){
throw new MyException(); // Line 8
}else{
System.out.println("Valid to access the application");
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
OUTPUT:
Exception: Age should be 18 to 35 years only
at com.test.MyApplication.main(MyApplication.java:8)
By above way we can define our own Exceptions for our application needs.