1. Overview
1.概述
In this short article, we’re going to show how to properly catch Java errors, and we’ll explain when it doesn’t make sense to do so.
在这篇短文中,我们将展示如何正确捕捉Java错误,并解释什么时候这样做是没有意义的。
For detailed information about Throwables in Java, please have a look at our article on Exception Handling in Java.
有关Java中可抛出的的详细信息,请看我们的文章Java中的异常处理。
2. Catching Errors
2.捕捉错误
Since the java.lang.Error class in Java doesn’t inherit from java.lang.Exception, we must declare the Error base class – or the specific Error subclass we’d like to capture – in the catch statement in order to catch it.
由于Java中的java.lang.Error类并不继承于java.lang.Exception,我们必须在catch语句中声明Error基类–或者我们想要捕获的特定Error子类,以便捕获它。
Therefore, if we run the following test case, it will pass:
因此,如果我们运行下面的测试案例,它将通过。
@Test(expected = AssertionError.class)
public void whenError_thenIsNotCaughtByCatchException() {
try {
throw new AssertionError();
} catch (Exception e) {
Assert.fail(); // errors are not caught by catch exception
}
}
The following unit test, however, expects the catch statement to catch the error:
然而,下面的单元测试希望通过catch语句来捕捉错误。
@Test
public void whenError_thenIsCaughtByCatchError() {
try {
throw new AssertionError();
} catch (Error e) {
// caught! -> test pass
}
}
Please note that the Java Virtual Machine throws errors to indicate severe problems from which it can’t recover, such as lack of memory and stack overflows, among others.
请注意,Java虚拟机抛出的错误表明它无法恢复的严重问题,例如内存不足和堆栈溢出,等等。
Thus, we must have a very, very good reason to catch an error!
因此,我们必须有一个非常、非常好的理由来捕捉一个错误!。
3. Conclusion
3.总结
In this article, we saw when and how Errors can be caught in Java. The code example can be found in the GitHub project.
在这篇文章中,我们看到了在Java中何时以及如何捕捉Errors。代码示例可以在GitHub项目中找到。