我有下面的代码,我在其中延迟加载类的实例创建。
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 实例,需要在其自己的构造函数中传递用户 ID、密码。如果假设我传递了错误的 uniApp 对象的用户 ID、密码,则不会创建 uniApp。这就是我需要的 -
我正在另一个类中调用 getInstance 方法 -
MyTest test=MyTest.getInstance();
在这里,我想添加如果发生uniApp创建失败的条件,废话。我怎么做? 一般来说,如果我试图在类 B 中调用在类 A 中引发异常的方法,并在 B 中放置一个条件 - 如果类 A 中的方法引发异常,请执行此操作。
我怎样才能实现这个目标?如果我的问题令人困惑,请告诉我。我可以编辑它:)
最佳答案
从你的私有(private)构造函数中抛出异常是可以的(引用 This SO question ,或者做一些快速的谷歌搜索)。在您的情况下,您捕获从 new UniApp()
抛出的异常,而不是将其传递 - 您可以非常轻松地将异常沿着食物链传递到您的 getInstance()
方法,然后调用该单例的任何人。
例如,使用您的代码:
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 block 包围对 getInstance()
的调用:
...
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()
的内容,因此我无法告诉您除此之外还可以做什么。
关于java - 调用在不同类中抛出异常的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21568083/