Skip to content

Month: December 2020

Short Tip on Java: throw multiple Exceptions at once

Reading Time: 5 minutes

Exceptions in Java are intended to interrupt the execution flow in unexpected situations. But there might be a need to continue the execution without interruption, still being able to collect all the errors that occurred before.

An abstract example of such a flow can be a Backup Manager. To increase reliability, it might need to save backups to multiple targets. Those can be a local file system, an external file system, and some cloud provider.

The whole flow will consist of three steps, one for each type of backup target. But the execution of these steps is unpredictable. Exceptions may happen at any moment, and the rest of the flow will be interrupted, which is bad, as one broken target may destroy the whole reliability concept.

Of course, Java has mechanisms to prevent interruption. Using try-catch block for each of the steps will guarantee that all the steps will be executed. The only problem here is that at the end of the execution there will be too little information about what went wrong.

Exceptions may be collected to some list and processed afterward. But in some cases, there is no need for such sophisticated solutions. The only needed outcome may be a single exception that will just explain the whole execution and what was wrong during it.

Leave a Comment