Friday 25 May 2012

User Defined Exception


1. Java provides an extensive set of in-build exceptions. But some cases we may need our own exception to handle some application specific error.

What is the neccessary to create our own exception?

1. The problem and Exception used may not have good relation.

2. If any unwanted condition or error occurs related to our Application, then we can throw our own application exception from any where.
[ While getting error in Helper classes, then we can not able to send that error directly to client.
That place, we can throw exception and send back to client ].


While defining an user defined exception, we need to take care of following,

1. The user defined exception class should extend from Exception class.
2. The toString() method should be overridden in user defined exception class inorder to provide meaningful information about the exception.


For Example,

public class UserDefinedException extends Exception {

    private String status;

    public UserDefinedException(String status) {
        this.status = status;
    }

    public String toString() {
        return "UserDefinedException : " + status;
    }

    public static void main(String args[]) {
        String str = null;
        try {
            checkInput(str);
        } catch (UserDefinedException ex) {
            System.out.println("Exception occured : " +ex);
        }
    }

    private static void checkInput(String input) throws UserDefinedException {
        if (input == null) {
            throw new UserDefinedException("Input is null");
        }
    }
}

In UserDefinedException class, We defined our own exception class.

In main method, we are checking whether the input is null, If its null then throwing 'UserDefinedException'.

If exception throws from called function, then need to catch that exception in caling function. [ Compiler will tell this ].


Difference between 'throw' and 'throws' :

throws :

1. It is used by the designer of a method to claim the exception. Claiming is nothing but informing the programmer about the potential problems that may arise while using the method.

2. The other way is to use as an alternative to try-catch block which is not a robust way.

throw :

1. "throw" is used by the programmer to throw an exception object explicitly to the system. Mostly used with user-defined exceptions.

No comments:

Post a Comment