How to create your own or custom Exception class in java?

Creating your own or custom Exception class in java is often needed when we handle different type of Exception in our coding. As we know we have two types of Exception Handling techniques one is Checked Exception and other is Unchecked Exception. So lets first see how we can create our own Checked Exception in java

Creating own Checked Exception in Java.



For creating your own checked Exception in java you need to inherit the java.lang.Exception class i.e. You can create the subclass of Exception class or subclass of Exception. In following example we have created CustomException class which extends Exception class. As in the code below we have added four constructors.

Custom Exception example in java



public class CustomException extends Exception  {
    
    public CustomException() { super(); }
    public CustomException( String message ) 
    { 
        super(message); 
        System.out.println("message = " + message);
        JOptionPane.showMessageDialog(null, "message = " + message);
    }
    public CustomException( String message, Throwable cause ) 
    { 
        super(message, cause); 
    }
    public CustomException( Throwable cause ) 
    {    
        super(cause); 
    }
    public String getLocalizedMessage() {
        return "This is a custome exception";
    }
}

To test this we have created one more class CustomExceptionTest where method such as validityCheck which is throwing or propagating this exception is declaring that it is throwing that Exception

public void validityCheck(int i) throws CustomException {


We are catching the CustomException class. Using that you can print the stacktrace , message or localized message etc. As we can see in CustomException class we are overriding the getLocalizedMessage() method to return our own message.

public class CustomExceptionTest {
    
    public static void main(String[] args) {
      try {
        int i = 5;
        CustomExceptionTest custExcepiontTest = new CustomExceptionTest();
        custExcepiontTest.validityCheck(0);
        
        Integer intCost = Integer.parseInt("test");
        
      } catch(CustomException ex) {
          System.out.println("ex "+ex.getMessage());
          System.out.println("ex localized message "+ex.getLocalizedMessage());
        //System.exit(1);
      } 
    }
    
    public void validityCheck(int i) throws CustomException {
    if (i < 2) {
        throw new CustomException("i < 0: " + i);
    }
}
}





Creating custom unchecked exception class in java




Sometimes you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException. For this you need to make changes in CustomException class such as
public class CustomException extends RuntimeException  {

When we extend the RuntimeException we dont need to declare the Exception implementation in throws clause. Lets see following example

public class CustomExceptionTest {
    
    public static void main(String[] args) {
      try {
        int i = 5;
        CustomExceptionTest custExcepiontTest = new CustomExceptionTest();
        custExcepiontTest.validityCheck(0);
        
        Integer intCost = Integer.parseInt("test");
        
      } catch(CustomException ex) {
          System.out.println("ex "+ex.getMessage());
          System.out.println("ex localized message "+ex.getLocalizedMessage());
        //System.exit(1);
      } catch(NumberFormatException ex) {
          throw new CustomException(ex);
      }
    }
    
    public void validityCheck(int i) {
    if (i < 2) {
        throw new CustomException("i < 0: " + i);
    }
}
}

In above example we can see two different things

1. We have validityCheck method without throws clause.
        public void validityCheck(int i) {

2. We are catching NumberFormatException but we are throwing exception as CustomException. This is how exception are encapsulated.

Unchecked exceptions are used for programmer's error, in cases where null is not checked, invalid argument being passed to the method or going out of array index etc.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment