Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 283
user200783 Avatar asked Feb 20 '16 02:02

user200783


1 Answers

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.

like image 147
heltonbiker Avatar answered Oct 06 '22 01:10

heltonbiker