Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:


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:

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.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Generic footer banner
Comments are closed on this article!