Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Will an Error Be Caught by Catch Block in Java?

$
0
0

1. Overview

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.

For detailed information about Throwables in Java, please have a look at our article on Exception Handling in Java.

2. Catching Errors

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.

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:

@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.

Thus, we must have a very, very good reason to catch an error!

3. Conclusion

In this article, we saw when and how Errors can be caught in Java. The code example can be found in the GitHub project.


Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>