且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以在java中捕获内存异常?

更新时间:2023-11-11 12:23:04

这不是例外;这是一个错误: java.lang.OutOfMemoryError

It's not an exception; it's an error: java.lang.OutOfMemoryError

您可以从Throwable下载:

You can catch it as it descends from Throwable:

try {
    // create lots of objects here and stash them somewhere
} catch (OutOfMemoryError E) {
    // release some (all) of the above objects
}

然而,除非你在做一些比较具体的东西一个特定的代码部分,例如)你可能无法抓住它,因为你不知道从哪里被抛出。

However, unless you're doing some rather specific stuff (allocating tons of things within a specific code section, for example) you likely won't be able to catch it as you won't know where it's going to be thrown from.