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'
Try and Except Statement – Catching all ExceptionsTry and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.
except is used to catch and handle the exception(s) that are encountered in the try clause. else lets you code sections that should run only when no exceptions are encountered in the try clause.
What is the reason for the try-except-else to exist? A try block allows you to handle an expected error. The except block should only catch exceptions you are prepared to handle. If you handle an unexpected error, your code may do the wrong thing and hide bugs.
Since Exception is the base class of all exceptions, it will catch any exception.
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
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