是否可以在java中捕获内存异常? [英] Is it possible to catch out of memory exception in java?
问题描述
我正在开发一个需要大量内存的程序,而当内存不足异常发生时,我想捕获。我听说这是不可能做的,但如果这方面有任何发展,好奇。
I'm developing a program that would require huge amount of memory, and I want to catch when out-of-memory exception happens. I had heard this is not possible to do, but curious if there is any development on this end.
推荐答案
这不是例外;这是一个错误: 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.
这篇关于是否可以在java中捕获内存异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!