Java:构造函数中抛出异常,我的对象还能被创建吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5909818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:23:44  来源:igfitidea点击:

Java: Exception thrown in constructor, can my object still be created?

javaexceptionconstructorlogic

提问by jitm

Could you tell me can be some case when exception is throwing in constructor and object is not null. I mean some part of object is created and another is not.Like this

当异常在构造函数中抛出并且对象不为空时,你能告诉我可能是什么情况。我的意思是对象的某些部分被创建而另一部分不是。像这样

public Test(){
name = "John";
// exception
// init some other data.
}

I understand in this sitiation object Test will be null, but Can be situation that object test cannot be null (delete block of exception not answer :) ) ?

我理解在这种情况下对象测试将为空,但可能是对象测试不能为空的情况(删除异常块不回答:))?

回答by Nathan Ryan

A class instance creation expression always creates a new object if the evaluation of its qualifier and arguments complete normally, and if there is space enough to create the object. It doesn't matter if the constructor throws an exception; an object is still created. The class instance creation expression does not complete normally in this case, though, as it propagates the exception.

如果类实例创建表达式的限定符和参数的计算正常完成,并且有足够的空间来创建对象,则它总是会创建一个新对象。构造函数是否抛出异常并不重要;仍然创建了一个对象。但是,在这种情况下,类实例创建表达式不会正常完成,因为它会传播异常。

However, you can still obtain a reference to the new object. Consider the following:

但是,您仍然可以获得对新对象的引用。考虑以下:

public class C {
    static C obj; // stores a "partially constructed" object
    C() {
        C.obj = this;
        throw new RuntimeException();
    }
    public static void main(String[] args) {
        C obj;
        try {
            obj = new C();
        } catch (RuntimeException e) {
            /* ignore */
        }
        System.out.println(C.obj);
    }
}

Here, a reference to the new object is stored elsewhere before the exception is thrown. If you run this program, you will see that the object is indeed not null, though its constructor did not complete normally.

在这里,在抛出异常之前,对新对象的引用存储在别处。如果你运行这个程序,你会看到对象确实不为空,尽管它的构造函数没有正常完成。

回答by Vladimir Ivanov

No. Look at the client code:

不,看客户端代码:

Test myObj = null;
try {
 myObj = new Test();
} catch(MyException e) {
  System.out.println("" + myObj);
}

Here, when exception occurs, the '=' operation is not executed. Your code goes straight to the catch block and myObj stays null.

这里,当发生异常时,不执行“=”操作。您的代码直接进入 catch 块,而 myObj 保持不变null

回答by Romain Linsolas

No. If exception occurs during the instantiation of the object, it will not be created.

不会。如果在对象的实例化过程中发生异常,则不会被创建。

Anyway, you would you write it?

无论如何,你会写吗?

MyObject obj = new MyObject();
// This code will not be reachable in case of an Exception

or:

或者:

MyObject obj = null;
try {
    obj = new MyObject();
} catch (AnyException e) {
}
// Here, either obj is created correctly, or is null as an Exception occurred.

回答by Pazhamalai G

public Test() {  
    name = "John"; 
    try {
        // exception 

        // init some other data.
    } catch(AnyException e) {
        // catch
    }
}

The above code makes sense as per your expectation.

上面的代码符合您的期望。