Andrew Guy Andrew Guy - 1 year ago 87
Python Question

Catching a (specific) generic Exception raised by an external library

I am using an external library which raises a generic

in one of it's modules under certain circumstances:

if some_condition:
raise Exception('DSSP failed to produce an output')

This only occurs in a few edge-cases, but is still something I want to catch and handle.

So, other than cursing the original coders for raising a generic
, what are my options here? I only want to catch and handle this particular line in the original code. What is the most Pythonic way of dealing with this?

Answer Source

Catch Exception and reraise if it's not the exception you're looking for:

except Exception as e:
    if type(e) is not Exception:
        # Not what we're looking for. Let it pass.

You can add some other checks if you want to really make sure it's the exception you're looking for, such as examining the exception's message.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download