Java creating custom Exceptions

Monday, August 4, 2008 12:16
Posted in category Java

Java supports the custom, user defined exception. Java provides the well known and common exception classes and gives freedom for developer to create their own exception classes matching to their specific business logic/role. For example, a user not found exception would be implemented by its own.

Download the Java Source code  for creating user custom exceptions

MyException.java  UserException.java

Step-1 Create the customized user exception, see the code below

public class UserException extends Exception{
String exception;
public UserException(){
super();
exception="Unknown";
}
public UserException(String exp){
super(exp);
this.exception=exp;
}
public String getException(){
return this.exception;
}
}

Step-2 Use the user created exception in your own class, see the code below.

public class MyException {
private String user=”";
private String password=”";
/**
* @param args
*/
public static void main(String args[]){
MyException my=new MyException();
try {
my.validateUser(”", “d”);
} catch (UserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void validateUser(String user, String passwd)throws UserException{
if(this.user==user && this.password==passwd){
System.out.println(”User Validated Successfully”);
}
else
throw new UserException(”Invalid User Found”);
}
}

Share and Enjoy:
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • blogmarks
  • Furl
  • Reddit
  • Spurl
  • StumbleUpon
  • Technorati
  • YahooMyWeb
  • Facebook
  • Live
  • Yahoo! Buzz
You can leave a response, or trackback from your own site.

One Response to “Java creating custom Exceptions”

  1. Muhammad Salman says:

    February 16th, 2010 at 10:31 am

    its easy and good.

Leave a Reply