How to robustly call third-party code in the presence of exceptions?

164 Views Asked by At

In a language which uses exceptions to signal errors, I want to call some third-party code and, if it fails, run fallback code instead. For example:

try:
    result = third_party.fast_calculation()
catch:
    result = slower_calculation()

In my experience, it is very rare to know all of the exceptions that could be thrown by the third-party code. Therefore I cannot list these exceptions in the catch clause. On the other hand, I am frequently advised not to catch every possible exception.

How should I write the catch clause in this situation?

2

There are 2 best solutions below

0
On

You should catch specific exception types only if you have a specific way to handle them. You can (and should) catch as many specific types of exception as needed, in the most appropriate order.

In case you just want to treat every exception the same way, I believe your current, untyped catch is as good as it gets. The real problem, IMO, comes when you leave an empty catch, since client code cannot know if the function actually did what it was supposed to do.

0
On

First, check that your third-party code actually throws exceptions. It may not.

Second, check the results returned if no exception is thrown by the third party code. A status value may be returned to indicate if a successful result was achieved. If so, a status check may be needed to determine if recovery actions (e.g. use the "slower_calculation" method) are needed after a bad return status.