Python except None

Python 3

def check_exceptions(exceptions=())
  try:                                                                            
    ...                                                                    
  except exceptions as e:                                                       
    ...                              

Works fine here (under Python 2.x).

>>> try:
...   foo
... except None as e:
...   pass
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'foo' is not defined

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.

source

Therefore the expression doesn't have to be an exception type, it will simply fail to ever match.

This behavior was changed in Python 3.x, and the expression after except must be a descendant of BaseException or a tuple of such.

Tags:

Python