Python except None

Are there any unexpected side effects from using "except None"? The behavior I expect is that nothing will be caught by this sentence, which several small tests seem to confirm.

Here is an example of what I'm trying to do. When an argument is not provided to a function, exceptions = None, which creates a "except None" clause. I just want to double check that I will not catch something unexpected.

# exceptions is exception or set of exceptions I want to do special processing for def check_exceptions(exceptions=None) try: ... except exceptions as e: ... 
+8
python
source share
1 answer

It works great 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, this expression is evaluated, and this clause corresponds to an exception if the resulting object is "compatible" with the exception. An object is compatible with an exception if it is the class or base class of the exception object, or a tuple containing an element compatible with the exception.

a source

Therefore, an expression should not be an exception type, it simply cannot match.

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

+8
source share

All Articles