Exception Part 2 – Customized Exceptions

Since all the exception in java are extended from exception class and counted as Objects, you can also extend the same way and generate your own exceptions, however most of them time existed standard exceptions are quite enough for application and normally it’s better to use the existed ones, but there are cases that you might need your own customized version of exceptions or currently existed ones might not address your need. so, in that case, you can simply extend from Exception class (and not from RunTimeException class) to make sure they could be unchecked Exceptions and also make sure you have a proper constructor for that.

about the constructors, you have below options …

  1. One without any parameters
  2. One with some details such as message
  3. one with some details such as message and the originally-thrown exception.

however you can define your own, but technically above constructors will satisfy most of the needs.

also Exception class itself provides almost everything you may need for further implementation, so remember to call super to use them, whenever you need.


public class MySpecialException extends Exception{

public MySpecialException(String reason, String additionalMessage){

super(reason + " = " +additionalMessage );}

}

public MySpecialException(String reason, String additionalMessage, Throwable e){

super(reason + " = " +additionalMessage, e );}

}

}

then inside your code you can easily call it like below snippet code.


public void myMethod() throws MySpecialException {

if(something happened wrong){
throw new MySpecialException("Reason of the issue","something really bad happened!");

}

 

try{

//opening a file for example

}catch(FileNotFoundException e){

throw new MySpecialException("Reason of the issue","something really bad happened!", e);

}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s