Saturday 12 March 2011

Creating Your Own or Custom Exception Classes in java

Making the exception class

class MyException extends Exception
{
String message;

//----------------------------------------------
// Default constructor - initializes instance variable to unknown

public MyException()
{
super(); // call superclass constructor
message = "No message,just for name";
}


//-----------------------------------------------
// Constructor receives some kind of message that is saved in an instance variable.

public MyException(String errMsg)
{
super(err); // call super class constructor
message= errMsg; // save message
}


//------------------------------------------------
// public method, callable by exception catcher. It returns the error message.

public String getMessage()
{
return message;
}
}


Throwing the above exception:


Consider the following method, which takes inputString and if its not "Vaani", it throws exception.



private void checkWord(String s) throws SpellException
{
if ("Vaani".equalsIgnoreCase(s))
System.out.println("OK");
else
throw new SpellException("Word is not Vaani");
}


Now suppose we are calling this method:


try
{
checkWord(); // this method throws SpellException
}
catch (MyException ex) // but it is caught here
{
System.out.println("Spell exception was: " + ex.getMessage());
}

No comments:

Post a Comment