java - 在 Java 中,当对象实例化失败时会发生什么?

标签 java object new-operator instantiation creation

我有 C++ 背景,我发现自己经常在 Java 中这样做:

SomeClass sc=new SomeClass();

if(null!=sc)
{
    sc.doSomething();
}

我想知道的是,如果构造函数由于某种原因(比如内存不足)而失败,变量 sc 中会有什么。我可以' 找不到直接的答案,我担心我只是在浪费时间,因为如果新运算符失败,程序是否会崩溃?

最佳答案

Java Specification Language 3rd Edition 彻底涵盖了您的问题:

12.5 Creation of New Class Instances

Whenever a new class instance is created, memory space is allocated for it with room for all the instance variables declared in the class type and all the instance variables declared in each superclass of the class type, including all the instance variables that may be hidden. If there is not sufficient space available to allocate memory for the object, then creation of the class instance completes abruptly with an OutOfMemoryError. Otherwise, all the instance variables in the new object, including those declared in superclasses, are initialized to their default values.

Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object using the following procedure: [...]

因此 new 表达式根本不可能返回 null。无论返回什么,如果执行正常完成,将始终是一个有效的 instanceof 无论类被实例化。


处理异常

一般来说,可能的异常通常用try-catch block 来处理:

String someString = askFromUser();
try {
   int num = Integer.parseInt(someString);
   doSomethingWith(num);
} catch (NumberFormatException e) {
   complainAboutIt();
}

在您的情况下,您可以考虑将 new SomeClass() 放入具有相应 catch (OutOfMemoryError e)try block 中,但是这是非常不典型的。除非您打算在这种情况发生时做一些有意义的事情,否则在大多数典型情况下,最好不要捕获任何Error。这可能会在您的程序执行期间发生。

来自文档:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.

A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.

相关问题

另见

关于java - 在 Java 中,当对象实例化失败时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3421606/

相关文章:

ios - 我的所有对象都在我的 iOS 模拟器中消失了,这是为什么?

java - 在 Java 中处理未初始化的字符串

java - 如果我需要初始化子类,如何使用抽象类?

c++ - 尝试打印值时出现 bad_alloc 异常

c++ - 静态工厂方法和静态对象内存泄漏

java - 连接到 .java 类的 .JSP 和 servlet

java - 用于指定调用哪个函数的字符串输入 [Java] [最佳实践]

c++ - 为什么不使用 "new"运算符创建的对象得到相同的地址

java - 检查是否有application.conf

javax.naming.NamingException : Name is not bound to a Context