Friday 9 January 2015

Creating Custom Exception Classes in Java

Hi Guys,
In this post we are going to see how to create an Custom Exception classes in Java.

Java provides a lot of exception classes for us to use but sometimes we may need to create our own custom exception classes to notify the caller about specific type of exception with appropriate message and any custom fields we want to introduce for tracking, such as error codes. For example, let’s say we write a java code for processing files and formatting number, so we can provide caller with appropriate error code when when file is not found and when we try to format a String to number.
Here is an example of custom exception class and showing it’s usage.

CustomException.java
package in.customexep;

public interface CustomException {

void processErrorCodes(MyException e) throws MyException;

void processFormatNumber() throws MyException;

void processFiles(String file) throws MyException;

}


MyException .java
package in.customexep;

public class MyException extends Exception {

private static final long serialVersionUID = 1L;

private String errorMessage="Unknown Exception";
 
    public MyException(String message, String errorMessage){
        super(message);
        this.errorMessage=errorMessage;
    }
   
    public String getErrorCode(){
        return this.errorMessage;
    }

}

CustomExceptionImpl .java
package in.customexep;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class CustomExceptionImpl implements CustomException {

public static void main(String[] args) throws MyException {
CustomException customExep = new CustomExceptionImpl();
try {
//customExep.processFiles("file.txt");
customExep.processFormatNumber();
        } catch (MyException e) {
        customExep.processErrorCodes(e);
        }
   
}

@Override
public void processErrorCodes(MyException e) throws MyException {
// TODO Auto-generated method stub
if(e.getErrorCode().equals("Number_Format_Exception"))
{
System.out.println("Number Format Exception Occured");
throw e;
}
else if(e.getErrorCode().equals("FILE_NOT_FOUND_EXCEPTION"))
{
System.out.println("FILE_NOT_FOUND_EXCEPTION Occured");
throw e;
}
else if(e.getErrorCode().equals("FILE_CLOSE_EXCEPTION"))
{
System.out.println("FILE_CLOSE_EXCEPTION Occured");
throw e;
}
else
{
System.out.println("Unknown exception occured, lets log it for further                       debugging."+e.getMessage());
            e.printStackTrace();
}

}

@Override
public void processFormatNumber() throws MyException {
// TODO Auto-generated method stub
try
{
String a ="ten";
int formatNumber = Integer.parseInt(a);
System.out.println(formatNumber);
}catch(NumberFormatException e)
{
throw new MyException(e.getMessage(), "Number_Format_Exception");
}

}

@Override
public void processFiles(String file) throws MyException {
// TODO Auto-generated method stub
InputStream fis = null;
        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new MyException(e.getMessage(),"FILE_NOT_FOUND_EXCEPTION");
        }finally{
            try {
                if(fis !=null)fis.close();
            } catch (IOException e) {
                throw new MyException(e.getMessage(),"FILE_CLOSE_EXCEPTION");
            }
        }

}

}

So, Now we run our program with processFormatNumber method. Here I am trying to convert the String to number format. Here i will get NumberFormatException because i am trying to convert String to number. Here is the Output.

That’s all for creating custom exception classes and handling in java, I hope you liked it and learned something from it.