Java:构造函数中抛出异常,我的对象仍然可以创建吗?
你能告诉我在构造函数中抛出异常并且对象不为空的情况下吗?我的意思是对象的某些部分被创建,而另一部分则没有。像这样,
public Test(){
name = "John";
// exception
// init some other data.
}
我理解在这种情况下对象 Test 将为 null,但可能是对象 test 不能为 null 的情况(删除异常块不回答:))?
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 :) ) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果类实例创建表达式的限定符和参数的计算正常完成,并且有足够的空间来创建该对象,则类实例创建表达式始终会创建一个新对象。构造函数是否抛出异常并不重要;仍然创建了一个对象。但是,在这种情况下,类实例创建表达式不会正常完成,因为它会传播异常。
但是,您仍然可以获得对新对象的引用。请考虑以下情况:
这里,在引发异常之前,对新对象的引用存储在其他位置。如果运行这个程序,您将看到该对象确实不为空,尽管它的构造函数没有正常完成。
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:
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.
没有。看一下客户端代码:
这里,当发生异常时,不执行'='操作。您的代码直接进入 catch 块,并且 myObj 保持
null
。No. Look at the client code:
Here, when exception occurs, the '=' operation is not executed. Your code goes straight to the catch block and myObj stays
null
.不会。如果对象实例化过程中发生异常,则不会创建该对象。
无论如何,你会写吗?
或者:
No. If exception occurs during the instantiation of the object, it will not be created.
Anyway, you would you write it?
or:
上面的代码符合您的期望。
The above code makes sense as per your expectation.