Q:

Detecting Exception Type

I have a set of exceptions defined that are being raised depending on the issue along with a custom message for the user. 
I would like to develop a mechanism of error handling using these custom exceptions and let them bubble up to a higher level logging class and eventually to the user so that we can provide feedback and tell them what to fix. It could even be the back end system crapping out, so they would know to come back a bit later. 
However, if it is not one of the manually created exceptions and it is a system exception (these are being raised, but wrapped in a custom exception), I would like to return a general error.
When I am handling my exception, what is a good way to detect if it is one of mine or something I didn't account for?
I was thinking of subclassing all my exceptions under a base one with a custom attribute and checking for it when letting the exception bubble up, but it seems kind of hacky. 
Thanks

A:

You can derive all exceptions from a single type. Many major Python libraries do this.
Now, see how I derived B from a shared base class?
class A(Exception):
    pass

class B(A):
    pass

Let's see if it works:
>>> try:
>>>     raise B
>>> except A:
>>>     print("Caught")
>>>     
Caught

And that it doesn't catch unrelated exceptions?
>>> try:
>>>     [][1]
>>> except A:
>>>     print("Caught")
>>>     
IndexError: list index out of range

Wonderful.
Inheritance is your friend: just subclass from a single base exception that you define, and you can try to catch this exception explicitly, log, and rethrow it. If it isn't from your library, then the error will not be caught.

