我有 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 ofThrowable
that indicates serious problems that a reasonable application should nottry
tocatch
. Most such errors are abnormal conditions.A method is not required to declare in its
throws
clause any subclasses ofError
that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.
相关问题
- Catching java.lang.OutOfMemoryError
- When to catch java.lang.Error?
- Is it possible to catch out of memory exception in java?
- Can the JVM recover from an OutOfMemoryError without a restart
- How to handle OutOfMemoryError in Java?
另见
关于java - 在 Java 中,当对象实例化失败时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3421606/