【发布时间】:2021-06-16 09:15:44
【问题描述】:
最近我被要求在我的代码中捕获 Throwable。 所以我们遇到了一个我们应该做还是不做的论点,我举了一个 OutOfMemoryError 的例子,在这种情况下,即使我们发现错误,我们的代码也不会被进一步处理。
所以为了测试这个理论,我们为它创建了示例代码。
public class TestErrorInThread {
public static void test() {
System.out.println("Running the test at time " + new Date());
try {
System.out.println("Inside try block");
Integer[] array = new Integer[10000000 * 10000000];
} catch (Throwable e) {
System.out.println("Inside catch block");
System.out.println(e);
}
int arr[] = new int[100];
System.out.println("Programme is still running...");
}
public static void main(String[] args) {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
Runnable runnable = TestErrorInThread::test;
scheduledExecutorService.scheduleAtFixedRate(runnable, 0, 5, TimeUnit.SECONDS);
}}
要运行我们使用以下命令的代码。
java -Xmx1m TestErrorInThread
我们得到了以下输出
在 IST 2021 年 6 月 16 日星期三 14:20:31 时间运行测试
内部尝试块
内部捕获块
java.lang.OutOfMemoryError:Java 堆空间
程序仍在运行...
在 IST 2021 年 6 月 16 日星期三 14:20:36 时间运行测试
内部尝试块
内部捕获块
java.lang.OutOfMemoryError:Java 堆空间
程序仍在运行...
在 IST 2021 年 6 月 16 日星期三 14:20:41 时间运行测试
内部尝试块
内部捕获块
java.lang.OutOfMemoryError:Java 堆空间
程序仍在运行...
在 IST 2021 年 6 月 16 日星期三 14:20:46 时间运行测试
内部尝试块
内部捕获块
java.lang.OutOfMemoryError:Java 堆空间
程序仍在运行...
在 IST 2021 年 6 月 16 日星期三 14:20:51 运行测试
内部尝试块
内部捕获块
java.lang.OutOfMemoryError:Java 堆空间
程序仍在运行...
为什么这个程序能够继续运行,即使它出现了内存不足的错误。
【问题讨论】:
-
程序的输出与理论不符,这里为什么JVM没有crash。
标签: java exception try-catch out-of-memory