是否可以在java中捕获内存不足异常? [英] Is it possible to catch out of memory exception in java?

查看:30
本文介绍了是否可以在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆