In most of the Java application we create application level exception classes depending on the application requirements. So in this example we are going to teach you how to write your own Exception class in Java. We can write a custom exception class in Java by exteding the Exception class.
The Concept
- Create your Exception Class file which extends Exception class.
- Call the super() in the argument less constructor of your exception class.
- Write the constructor with an argument of class Throwable.
- Override the toString() and getMessage() methods.
Now lets see the example code of our own exception class.
Example code of Custom Exception Class In Java
public class MyException extends Exception
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String message = null;
public MyException() {
super();
}
public MyException(String message) {
super(message);
this.message = message;
}
public MyException(Throwable cause) {
super(cause);
}
@Override
public String toString() {
return message;
}
@Override
public String getMessage() {
return message;
}
}
Above Java class (MyException.java) is our custom Exception class which extends the Exception class. Now this below Java class will explain how to use this custom exception class.
Client Code
public class CustomExceptionInJava
{
public static void main(String args[])
{
CustomExceptionInJava mybj = new CustomExceptionInJava();
try
{
mybj.exceptionExample(null);
}
catch (MyException e)
{
System.out.println("Example of Java Custom Exception Class: " + e.getMessage());
}
}
private void exceptionExample(String data) throws MyException
{
if(data==null || data.length()==0)
{
throw new MyException("Data is not supplied or its null.");
}
}
}
Output
Above example explains how to use the custom exception class in your client code.
In your custom exception class you can override the required methods from the parent class. Like in this example we have overridden getMessage() method from parent class, you can also override other available methods in parent class if required.
You can consider this as a base example for your application and similarly write your own exception classes according to your application requirements.
The post How to Write your Own Java Exception Class appeared first on Jafaloo - The Tech Blog.