首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >方法,该方法在不同的类中抛出异常。

方法,该方法在不同的类中抛出异常。
EN

Stack Overflow用户
提问于 2014-02-05 03:28:43
回答 1查看 3.9K关注 0票数 2

下面的代码是延迟加载类实例创建的代码。

代码语言:javascript
运行
复制
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;
}

在构造函数中,我正在创建一个UniApp实例,它要求在自己的构造函数中传递用户I、密码。如果我传递了一个错误的uniApp对象的用户I,密码,uniApp就不会被创建。我需要的是-

我在一个不同的类中调用getInstance方法-

代码语言:javascript
运行
复制
    MyTest test=MyTest.getInstance();

在这里,我想添加一个条件,如果uniApp的创建失败了,那就去做吧。我该怎么做?通常,如果我试图调用一个方法,该方法在B类的A类中抛出异常,并在B中添加一个条件--如果A类中的方法抛出异常,则执行以下操作。

我怎样才能做到这一点?如果我的问题令人困惑,请告诉我。我可以编辑它:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-05 03:51:10

从您的私有构造函数中抛出一个异常是可以的(参考This SO question,或者快速搜索)。在您的示例中,您正在捕获从new UniApp()抛出的异常,而不是将其传递--您可以很容易地将该异常传递到食物链中,然后将其传递到您的getInstance()方法中,然后由谁来调用该单例。

例如,使用您的代码:

代码语言:javascript
运行
复制
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;
}

若要创建"if“条件以测试getInstance()方法是否有效,请使用try/catch块包围对getInstance()的调用:

代码语言:javascript
运行
复制
...
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
}
...

由于您还没有展示什么是真正的MyTest.getInstance(),所以我无法告诉您除此之外还应该做什么。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21568083

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档