About NewTechnoBuzz
Advertise
Contact Us

Monday, July 7, 2014

Create Custom Exception in Java

Exception is an error event that can happen during the execution of a program and disrupts its normal flow. Java provides a robust and object oriented way to handle exception scenarios, known as Java Exception Handling.
But sometimes, we need to create custom exceptions in Java, i.e. exceptions which are not defined in JDK. Though it’s widely recommended that we should prefer standard exception over custom exception, but sometime we really need it.

When user feels that he wants to use its own application specific exception for some reasons, user can create a new class extending appropriate super class (mostly its Exception class) and start using it in appropriate places. These user defined exceptions can be used in two ways:

  • Either directly throw the custom exception when something goes wrong in application
throw new DaoObjectNotFoundException("Couldn't find dao with id " + id);
  • Or wrap the original exception inside custom exception and throw it
catch (NoSuchMethodException e) {
  throw new DaoObjectNotFoundException("Couldn't find dao with id " + id, e);
}

Wrapping an exception can provide extra information to the user by adding your own message, while still preserving the stack trace and message of the original exception. It also allows you to hide the implementation details of your code, which is the most important reason to wrap exceptions.

Below is an example of custom exception class and showing it’s usage.

MyCustomException.java

package com.gsms.core.common.custom.exceptions;
 
public class MyCustomException extends Exception {
 
    private static final long serialVersionUID = 4589241582659741528L;
     
    private String errorCode="Unknown";
     
    public MyCustomException(String errMsg, String errorCode){
        super(errMsg);
        this.errorCode=errorCode;
    }
     
    public String getErrorCode(){
        return this.errorCode;
    }
}

MyCustomExceptionDemo.java

package com.gsms.core.common.custom.exceptions;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
 
public class MyCustomExceptionDemo {
 
    public static void main(String[] args) throws MyCustomException {
        try {
            readFile("test.txt");
        } catch (MyCustomException e) {
            displayErrorCodes(e);
        }
     
    }
 
    private static void displayErrorCodes(MyCustomException e) throws MyCustomException {
        switch(e.getErrorCode()){
        case "BAD_FILE_TYPE":
            System.out.println("Bad File Type");
            throw e;
        case "FILE_NOT_FOUND_EXCEPTION":
            System.out.println("File Not Found");
            throw e;
        case "FILE_CLOSE_EXCEPTION":
            System.out.println("File Close failed");
            break;
        default:
            System.out.println("Unknown exception occured."+e.getMessage());
            e.printStackTrace();
        }
    }
 
    private static void readFile(String file) throws MyCustomException {       
        InputStream fis = null;
        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new MyCustomException(e.getMessage(),"FILE_NOT_FOUND_EXCEPTION");
        }finally{
            try {
                if(fis != null)fis.close();
            } catch (IOException e) {
                throw new MyCustomException(e.getMessage(),"FILE_CLOSE_EXCEPTION");
            }
        }
    }
}

I am extending Exception so that whenever this exception is being produced, it has to be handled in the method or returned to the caller program, if we extends RuntimeException, there is no need to specify it in the throws clause.


Please feel free to post your comments and queries. In case, you some good information, please share with us.

0 comments