Java:在构造函数中抛出异常,我的对象是否仍然可以创建? [英] Java: Exception thrown in constructor, can my object still be created?

查看:135
本文介绍了Java:在构造函数中抛出异常,我的对象是否仍然可以创建?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能告诉我一些情况下,异常抛出的构造函数和对象不为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.
}



我理解在这个位置对象测试将是null,对象测试不能为null(删除块异常不回答:))

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 :) ) ?

推荐答案

类实例创建表达式总是创建一个新的对象,如果其限定符和参数的求值正常完成,以及是否有足够的空间来创建对象。无论构造函数是否抛出异常;仍然创建对象。但是,在这种情况下,类实例创建表达式无法正常完成,因为它传播了异常。

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);
    }
}

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

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.

这篇关于Java:在构造函数中抛出异常,我的对象是否仍然可以创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆