为什么没有捕获"java.lang.OutOfMemoryError:Java堆空间"?

Cri*_*spy 10 java try-catch out-of-memory

我在Java Web应用程序中有一个线程导致java.lang.OutOfMemoryError:Java堆空间异常,但try/catch块没有捕获错误.

示例代码:

private void doSomeWork()
{
     try
     {
         processData();  //Causes OutOfMemoryError
         System.out.println("This line does not execute");
     }
     catch (Exception e)
     {
         System.out.println("Exception.  This line does not execute.");
         //Log error
     }
     finally
     {
         System.out.println("finally.  This line does execute");
         System.out.println("Thread name: " + Thread.currentThread().getName());

     }
}
Run Code Online (Sandbox Code Playgroud)

输出:

finally.  This line does execute 
Thread name: _Worker-8
Exception in thread "_Worker-8" java.lang.OutOfMemoryError: Java heap space
...

背景:

我最近接手了这个Java项目,我正在努力加快Java和这个项目的速度.我是C#开发人员,所以我还不熟悉这个项目或Java.我知道我可以使用-Xmx设置修复错误,但我有兴趣捕获此错误,以便我可以记录它.错误未显示在任何日志文件中,并且输出在Eclipse中以调试模式显示在控制台中.

Kal*_*see 40

因为OutOfMemoryErrorError,不是Exception.由于OutOfMemoryError不是子类Exception,因此catch (Exception e)不适用.

OutOfMemoryErrorThrowable然而,确实延伸了,所以你应该能够抓住它.这是关于何时(如果有的话)你应该捕获错误的SO讨论.通常,由于您无法对此做任何事情,因此建议不要在生产代码中捕获错误.但是考虑到一个特殊情况,你试图调试正在发生的事情,它可能会有所帮助.

  • 我建议在应用程序的最外层部分(或在线程方法的最外层部分)捕获throwables,这样你就可以真正知道为什么你的程序已经中止了(如果没有其他人会为你做这件事) . (2认同)

Mas*_*ari 11

java.lang.OutOfMemoryError不扩展java.lang.Exception,因此它不是Exception.OutOfMemoryError扩展了java.lang.Error.如果你想捕捉错误试试这个:

private void doSomeWork()
{
     try
     {
         processData();  //Causes OutOfMemoryError
         System.out.println("This line does not execute");
     }
     catch (Error e)
     {
         System.out.println("Exception.  This line does not execute.");
         //Log error
     }
     finally
     {
         System.out.println("finally.  This line does execute");
         System.out.println("Thread name: " + Thread.currentThread().getName());

     }
}
Run Code Online (Sandbox Code Playgroud)

注意:异常和错误扩展为Throwable,因此您也可以使用Throwable来捕获它们.

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Throwable.html