Question

I have the below code where I am lazy loading the instance creation of my class.

public class MyTest {
private static MyTest test = null;
private UniApp uniApp;  

private MyTest(){
    try{                        
        uniApp = new UniApp("test","test123");          
    }
    catch(Exception e){
        e.printStackTrace();
        logger.error("Exception " +e+ "occured while creating instance of uniApp");
    }   
}

public static MyTest getInstance(){
    if (test == null){
        synchronized(MyTest.class){
            if (test == null){
                test = new MyTest();
            }
        }
    }
    return test;
}

In the constructor, I am creating an instance of UniApp that requires passing userid, password in its own constructor. If lets say I pass a wrong userid, password of the uniApp object, uniApp doesn't get created. Here is what I need -

I am invoking the getInstance method in a different class -

    MyTest test=MyTest.getInstance();

And here, I want to add condition if failure of creation of uniApp happens, do blah. How do I do that? In general, if I am trying to invoke a method that throws an exception in class A in class B, and put a condition in B - if the method in class A throws exception, do this.

How can I achieve this? Let me know if my question is confusing. I can edit it :)

Was it helpful?

Solution

Throwing an exception from your private constructor would be ok (reference This SO question, or do some quick Googling). In your case, you are catching the exception thrown from new UniApp() and not passing it along - you can very easily pass that exception up the foodchain into your getInstance() method and then to whomever calls that singleton.

For instance, using your code:

private MyTest() throws UniAppException { // Better if you declare _which_ exception UniApp throws!
    // If you want your own code to log what happens, keep the try/catch but rethrow it
    try{                        
        uniApp = new UniApp("test","test123");          
    }
    catch(UniAppException e) {
        e.printStackTrace();
        logger.error("Exception " +e+ "occured while creating instance of uniApp");
        throw e;
    }   
}

public static MyTest getInstance() throws UniAppException {
    if (test == null) {
        synchronized(MyTest.class) {
            if (test == null) {
                test = new MyTest();
            }
        }
    }
    return test;
}

To create your "if" condition to test whether the getInstance() method works or not, surround your call to getInstance() with a try/catch block:

...
MyTest myTest;
try {
    myTest = MyTest.getInstance();
    // do stuff with an instantiated myTest
catch (UniAppException e) {
    // do stuff to handle e when myTest will be null
}
...

Since you haven't shown what actually calls MyTest.getInstance() I can't tell you what else to do besides that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top