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.
0 comments