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

发布于 2024-09-12 18:38:23 字数 238 浏览 3 评论 0原文

我来自 c++ 背景,我发现自己经常在 java 中这样做:

SomeClass sc=new SomeClass();

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

我想知道的是,如果构造函数由于某种原因失败(比如可能没有足够的内存),变量 sc 中将会有什么。我可以' 找不到直接的答案,我担心我只是在浪费时间,因为也许如果新的操作员失败,程序就会崩溃吗?

I come from a c++ background and I find myself constantly doing this in java:

SomeClass sc=new SomeClass();

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

What I want to know is what will be in the variable sc if the constructor fails for some reason (like maybe not enough memory). I can'
t find a straight answer, and I am worried that I am just wasting my time because maybe if the new operator fails would the program just crash anyway?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

筱武穆 2024-09-19 18:38:23

Java 规范语言第三版彻底涵盖了您的问题:

12.5 创建新类实例

每当创建一个新的类实例时,都会为其分配内存空间,其中包含该类类型中声明的所有实例变量以及该类类型的每个超类中声明的所有实例变量,包括所有可能的实例变量。被隐藏。如果没有足够的空间可用于为对象分配内存,则类实例的创建会突然完成,并显示 OutOfMemoryError。否则,新对象中的所有实例变量(包括超类中声明的实例变量)都将初始化为其默认值。

在对新创建的对象的引用作为结果返回之前,将使用以下过程处理指定的构造函数以初始化新对象:[...]

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


处理异常

一般来说,可能的异常通常使用 try-catch 块进行处理:

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

根据您的情况,您可以考虑将 new SomeClass() 放入 try< /code> 块带有相应的 catch (OutOfMemoryError e),但这非常不典型。除非您打算在发生这种情况时做一些有意义的事情,否则在大多数典型情况下,最好不要捕获任何错误 可能在程序执行过程中发生。

从文档中:

ErrorThrowable 的子类,它指示合理的应用程序不应尝试捕获的严重问题>。大多数此类错误都是异常情况。

方法不需要在其 throws 子句中声明在方法执行期间可能抛出但未被捕获的 Error 的任何子类,因为这些错误是不应该发生的异常情况。

相关问题

另请参阅

  • < a href="http://download-llnw.oracle.com/javase/tutorial/essential/exceptions/index.html" rel="noreferrer">Java 教程/异常

The Java Specification Language 3rd Edition covers your question thoroughly:

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: [...]

So it's simply not possible for a new expression to return null. Whatever is returned, if the execution completes normally, will always be a valid instanceof whatever class was instantiated.


Handling exceptions

Generally speaking, possible exceptions are usually handled with a try-catch block:

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

In your case, you may consider putting new SomeClass() in a try block with a corresponding catch (OutOfMemoryError e), but this is highly atypical. Unless you plan to do something meaningful when this happens, in most typical scenarios it's best to not catch any Error that may occur during your program execution.

From the documentation:

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.

Related questions

See also

帥小哥 2024-09-19 18:38:23

如果构造函数失败,那么它将抛出异常或错误,并且您将无法进一步了解程序。具体来说,如果内存不足,您将收到 OutOfMemoryError

If the constructor failed, then it would throw an exception or an error and you wouldn't get any further in the program. Specifically, if it ran out of memory, you would get an OutOfMemoryError.

比忠 2024-09-19 18:38:23
SomeClass sc=new SomeClass();

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

创建对象后,对象引用永远不会为 null,因此不需要 null 检查,因为条件始终为 true。

例如,如果构造函数中的该点没有足够的内存,则会抛出 OutOfMemoryError 并且构造函数将无法正常返回。

SomeClass sc=new SomeClass();

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

An object reference is never null after creating an object, so the null check is unnecessary because the condition will always be true.

If, for example, there is not enough memory at the point in the constructor, an OutOfMemoryError will be thrown and the constructor will not return normally.

猫性小仙女 2024-09-19 18:38:23

是的,你在浪费时间:-)。调用构造函数后,sc 保证为非空。如果构造函数失败,则会抛出异常,并且以下代码将永远不会运行。因此,以下内容在 Java 中是安全的:

SomeClass sc = new SomeClass();
sc.doSomething();

不会抛出 NullPointerException。

Yes you are wasting your time :-). sc is guaranteed to be non-null after the constructor is called. If the constructor failed an exception would be thrown and the following code would never be run. Hence the following is safe in Java:

SomeClass sc = new SomeClass();
sc.doSomething();

without throwing a NullPointerException.

×眷恋的温暖 2024-09-19 18:38:23

不需要该 if 检查,有些 IDE 甚至会抱怨这是不必要的,因为它的计算结果始终为 truenew 失败的唯一原因是构造函数抛出异常,在这种情况下,您的 if 检查无论如何都会被绕过。

That if check is not needed, and some IDEs will even complain that it is unnecessary as it always evaluates to true. The only reason that new would fail is if the constructor threw an exception, and in that case your if check will be bypassed anyways.

各自安好 2024-09-19 18:38:23

抛出 OutOfMemoryError ,这将通常会导致虚拟机崩溃。
(可能被捕获为 Throwable)

您可能会发现 阻止并恢复Java OutOfMemory 错误 很有用。

An OutOfMemoryError is thrown which will usually crash the virtual machine.
(Could be catched as Throwable)

You might find Prevent and Recover from Java OutOfMemory Error useful.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文