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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With