Try/Multi-Catch vs Single Catch

tl;dr Mutlicatch handles things singlehandedly, multiple catch blocks are more flexible and nicer to operations. The two techniques can be combined.

If you have a try statement that can throw many different exception types, you'll want the multiple catch blocks. It's a bit more code but offers far greater flexibility.

For instance, if working with sockets, a SocketException may be caught with nothing more than a reconnect and/or an error message (as something as simple as an inadvertently disconnected cable may cause this)

If a null pointer exception(although it's unchecked) is caught, you're going to want to write to a log and make an emergency landing here, cleaning up what you can, and backtracking quite a bit codewise, possibly.

In addition, this can be subdivided even further, where different types of "common" exceptions may cause different actions to be taken(such as a connection lost vs name not resolved having different implications for the end-user on the first connection attempt) and different "heavy" exceptions being handled in different ways as well.

While you could have one (multiple exception type) catch block, it would either singlehandedly take similar action for all exceptions (presenting a null pointer exception to a user in the same way as a condition based on a cable being unplugged) or require if e instanceof FooException blocks that can decrease readability.

You can also combine the two, multicatching all "common" exceptions into a retry and nice message and all severe exceptions into a forced cleanup and shutdown

You don't want stacktraces for tripped cables, and you don't want to brush off missing objects.


This a choice thing. You want to balance readability, portability, maintainability and also handling different exceptions differently.

So balance the use ... If all your catches use the same block of handling then use the first form, because that's just one code block and you aren't repeating yourself over and over again. The compiler can optimize things out a bit for you.

On the other hand use the second form if you are handling each exception differently.

This is somewhat of a broad question and the answer is dependant on your goals.

Tags:

Java

Try Catch