Friday, June 14, 2013

Creating custom exceptions in Java

Hi All,
Welcome to Java-recent.
In this we will discuss how to create custom Exceptions.
We have seen lot of built in Exceptions like NullPointerExceptions,IOException   etc. All of them extends Exception class. For a Java class to become  a custom exception class it needs to extend Exception class.


Custom Exceptions:- They are primarily used to put user defined exception messages.
Suppose login has failed in a web application,then application need to throw custom error message as Invalid login etc. This can be achived creating custom Exception messages.

Note:- Custom exception classes should always be placed in a separate package.


Example:-

public class ExceptionExample {
public void validateEmpName(String empName) throws UserNotFound
{
if(!empName.equals("Java-recent"))
{
throw new UserNotFound();
}
}
public static void main(String[] args) {
ExceptionExample ee=new ExceptionExample();
try {
ee.validateEmpName("Google");
} catch (UserNotFound e) {
// TODO Auto-generated catch block
System.out.println("Exception occured "+e.getMessage());
//e.printStackTrace();
}
}
}

UserNotFound.java
public class UserNotFound extends Exception {
public UserNotFound()
{
super("Invalid user name");
}
}


Output :-
Exception occured Invalid user name

In the validateEmpName method we are validating user name and throwing custom Exception UserNotFound() and catched it in main method.

The message in UserNotFound() constructor will act as Exception message.

                      Happy Learning

Please provide your valuable comments on this article and share it across your network.




No comments:

Post a Comment

Like and Share