gpt4 book ai didi

java - 如果 new 失败了怎么办?

转载 作者:搜寻专家 更新时间:2023-10-30 20:58:12 26 4
gpt4 key购买 nike

在 C++ 和 C# 中,当 new 无法分配足够的内存时,它会抛出异常。

我找不到有关 new 在 Java 中的行为的任何信息。那么如果在Java中new失败(内存不足)会怎样呢?

最佳答案

假设您具体是指内存分配失败,那么它应该抛出 OutOfMemoryError

Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

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. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

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 - 如果 new 失败了怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4785343/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com