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

In a language that uses exceptions for signal errors, I want to call some third-party code, and if it doesn't work, run the backup code instead. For example:

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

In my experience, it is very rare to find out all the exceptions that may be caused by third-party code. Therefore, I cannot list these exceptions in the catch clause. On the other hand, I am often not encouraged to catch all possible exceptions.

How do I write a catch clause in this situation?

+7
language-agnostic exception exception-handling robustness
source share
2 answers

You should catch certain types of exceptions only if you have a specific way to handle them. You can (and should) catch as many special types of exceptions as possible in the most appropriate order.

If you just want to treat all exceptions the same way, I think your current, untyped catch is as good as it is. The real problem, IMO, arises when you leave an empty catch, because the client code cannot know if the function really did what it was supposed to do.

+1
source share

First check to see if your third-party code actually throws exceptions. It may not be.

Secondly, check the returned results if the exception is not sent by the third code. A status value may be returned to indicate whether a successful result has been achieved. If this is the case, a state check may be required to determine if recovery actions are necessary (for example, using the slow_calculation method) after a bad return status.

0
source share

All Articles