Catching OutOfMemoryError

2019-02-12 22:59发布

Is there any point catching an out of memory error (java.lang.OutOfMemoryError) in Java?

9条回答
疯言疯语
2楼-- · 2019-02-12 23:51

The golden rule is to only catch errors that you can handle. If you can do something useful after an OutOfMemory error, then go ahead.

查看更多
【Aperson】
3楼-- · 2019-02-12 23:51

No, catch Exception and RuntimeException, but hardly ever (changed from 'never') 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.

Note:
I'm quoting the official Javadocs here. If you don't agree, tell Oracle, don't shoot the messenger :-)

查看更多
女痞
4楼-- · 2019-02-12 23:51

If you want to have a graceful shutdown which handles this case specificly.

You can also use it if you may have to allocate a large array and you want to gracefully degrade your system.

EDIT: An example of code where I used to check OOM if the stream was corrupted. I have since replace the len check to ensure the len is between 0 and 16 MB instead.

DataInputStream dis = new DataInputStream(socket.getInputStream());

public byte[] readBytes() {
  int len = dis.readInt();
  try {
    byte[] bytes = new byte[len];
    dis.readFully(bytes);
    return bytes;
  } catch(OutOfMemoryError e) {
    log.error("Corrupt stream of len="+len);
    closeSocket();
    return null;
  }
}
查看更多
登录 后发表回答