Exception handling for junior devs

Exception handling is a very important thing for creating production ready code.
When you are a brand new developer you might not know how to do exception handling properly.
Here I will try to describe a few basic rules that should be followed when coding.
Please note that as always there might be reasons for breaking these rules, but they are a sane default.

The rules here can be used for java and c#.

Exceptions should be exceptional

Don't use exceptions for normal program flow.
In normal program flow use simple return statements.
why: Because exceptions were not made for normal program flow and hence they can be a very slow. Furthermore the program flow is a lot harder to follow when exceptions are flowing around as a few methods might be skipped.
cure: Use normal program flow mechanisms for this.

Don't use Pokémon exception handling

You know the themesong from Pokémon: "Gotta catch them all" - well it may hold true when in the Pokémon universe, but when doing exception handling it rarely does.

Don't catch Exception.

why: If you catch Exception it is a strong communication that you do not know what you are doing which exceptions you are expecting.
And furthermore future exceptions that you do not know about will be handled
cure: Handle the specific exceptions that you know about and expect.

Don't swallow exceptions

Swallowing exceptions means catching an exception and doing nothing.
why: Only if you really know that this is by intention and always leave a comment as to why you swallow the exception. Not just a //do nothing by intention, but a real explanation.
Swallowing exceptions denies your future self the opportunity to debug the problem in production.
cure: Only handle exceptions you can actually handle

If you cannot do anything to an exception don't handle it

Let someone else handle it.
why: you are just adding extra code and taking away the chance to handle the exception where it actually has meaning
cure: Don't do anything where you cannot handle the exception, but do find another place where it makes sense. If you cannot find a place to handle the exception, maybe you have a problem in your code?

But maybe you should do some logging... But ...

Don't log an exception if you cannot handle it

why: If you log where you cannot handle it you will clutter the log and add no context.
cure: Log when you handle exceptions and add some context.

comments powered by Disqus