Thursday 4 April 2013

Example for how to create a User Defined Exception and how can we use that


Example for how to create a User Defined Exception and how can we use that

For Creating a User Defined Exception, at first we need to extend Exception class. Then we have to override toString() method in the User Defined Exception class. Below is the example of a User Defined Exception.

SingletonException

public class SingletonException extends Exception{
    private String message;
    public SingletonException(String msg){
        this.message = msg;
    }
    public String toString(){
        return message;
    }
}

In the Below class, I am going to call the above User Defined exception class when User will try to create more than one instance of singletontest class.

SingletonClassExample

//  A Singletontest is a class which is based on Singleton Design pattern. So user can create only one instance of Singletontest class and if user will try to create another instance then it will throw SingletonException.

class Singletontest {
    private static Singletontest instanceObj;

    private Singletontest() {
        System.out.println("This is a constructor call");
    }

    public static Singletontest getInstance() throws SingletonException {
        if (instanceObj == null) {
            instanceObj = new Singletontest();
        } else {
            throw new SingletonException(
                    "Already instance of this class is created,Another instance is not allowed");
        }
        return instanceObj;
    }
}

public class SingletonClassExample {
    public static void main(String args[]) {
        try {
            Singletontest test1 = Singletontest.getInstance();
            System.out.println("This is 1st instance--" + test1);
            Singletontest test2 = Singletontest.getInstance();
            System.out.println("This is the 2nd Instance->" + test2);

        } catch (SingletonException e) {
            System.out.println(e);
        } finally {
            try {
                Singletontest test3 = Singletontest.getInstance();
                System.out.println("This is the 3rd Instance->" + test3);
            } catch (SingletonException e) {
                System.out.println(e);
            }
        }
    }
}

No comments:

Post a Comment