How to know about OutOfMemory or StackOverflow errors ahead of time

前端 未结 11 1710
余生分开走
余生分开走 2021-02-15 17:10

In Java, is there a way to know that a StackOverflow error or OutOfMemory exception may happen soon?

The OutOfMemory exception m

11条回答
  •  广开言路
    2021-02-15 17:33

    You could discover a lot about recursion depth, by creating a Throwable object, and querying its getStackTrace() method. But this is expensive to do.

    If you really have a method with a small potential of throwing a StackOverflowError or an OutOfMemoryError why not just insert try-catch blocks and catch those errors? They can be caught and handled just like checked exceptions.

提交回复
热议问题