Tip: Gracefully handle exceptions by introducing the same exception

Paul Marsh
1 min readNov 1, 2021

--

When you write a reasonably large application then you will get exceptions. One source of information about these problems are diagnostic log files. However, just because you can see that an exception has been reported it is not always obvious what state the wider system was in to trigger the problem. This presents two problems; 1) What caused the problem 2) How to gracefully handle the exception. My tip here concerns the latter, how can we be sure that any new code we introduce correctly handles the problem if we are not sure how to reproduce the issue?

Temporarily add the same exception

The trick is really quite simple. The diagnostics will typically at least tell you where the exception originated from. So rather than recreating the exception by trying to get the system into the same state, simple add code to throw/raise exception at the same point. This way you can create the same flow of exception handlers and ensure the code gracefully continues without causing the application any serious problems. Once the exception is handled correctly remember to remove the artificial exception :)

--

--