Exception Handling

Understand how to handle exceptions in JUnit 5.

We'll cover the following

Swallow IOException

We can use custom extensions to handle exceptions thrown during test executions. The extension interface for exception handling is TestExecutionExceptionHandler. It only has one method, void handleTestExecutionException(Extensicontext, Throwable throwable) throws Throwable. The Throwable parameter contains the thrown exception. In the implementation of the handleTestExecutionException method, we can perform one of the following tasks:

  • Swallow the thrown exception and stop propagation.
  • Re-throw the thrown exception as-is.
  • Throw a new exception that may wrap the thrown exception. In the code below, we create a TestExecutionExceptionHandler that swallows the IOExceptions in line 12.

Get hands-on with 1400+ tech skills courses.