Evan
Evan

Reputation: 557

Why doesn't except object catch everything in Python?

The python language reference states in section 7.4:

For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is the class or a base class of the exception object, or a tuple containing an item compatible with the exception.

So, why doesn't except object: catch everything? object is the base class of all exception classes, so except object: should be able to catch every exception.

For example, this should catch the AssertionError

print isinstance(AssertionError(), object) # prints True
try:
    raise AssertionError()
except object:
    # This block should execute but it never does.
    print 'Caught exception'

Upvotes: 14

Views: 716

Answers (1)

Tadhg McDonald-Jensen
Tadhg McDonald-Jensen

Reputation: 21453

I believe the answer can be found in the source code for python 2.7:

        else if (Py_Py3kWarningFlag  &&
                 !PyTuple_Check(w) &&
                 !Py3kExceptionClass_Check(w))
        {
            int ret_val;
            ret_val = PyErr_WarnEx(
                PyExc_DeprecationWarning,
                CANNOT_CATCH_MSG, 1);
            if (ret_val < 0)
                return NULL;
        }

so if w (I assume the expression in the except statement) is not a tuple or exception class and the Py_Py3kWarningFlag is set then trying to use an invalid exception type in the except block will show a warning.

That flag is set by adding the -3 flag when executing your file:

Tadhgs-MacBook-Pro:~ Tadhg$ python2 -3 /Users/Tadhg/Documents/codes/test.py
True
/Users/Tadhg/Documents/codes/test.py:5: DeprecationWarning: catching classes that don't inherit from BaseException is not allowed in 3.x
  except object:
Traceback (most recent call last):
  File "/Users/Tadhg/Documents/codes/test.py", line 4, in <module>
    raise AssertionError()
AssertionError

Upvotes: 3

Related Questions