`try ... except not` construction
EDIT: The answer below was for Python 3, I didn't realise the question related to Python 2.7. in Python 2, as it seems, the interpreter does not complain if the expression after except
does not result in a subtype of BaseException
. However, the behavior is still wrong, it will just ignore that except
block in all cases.
That's a funny construction that is syntactically valid but semantically wrong. I suppose the author of the code meant to express something like "run this except
block for any exception type but ExampleError
". However, what is really happening is more like:
try:
# ...
except (not bool(ExampleError)):
# ...
When an exception is raised in the try
block, Python goes through the different except
blocks looking for one that matches the exception type. When it sees except not ExampleError
, equivalent to except (not bool(ExampleError))
, it results in except False
, which is invalid because False
is not a subtype of BaseException
(or a tuple of subtypes of BaseException
). So the code may even run if no exceptions are raised but is wrong.
This is not going to be successful on any version of Python as far as I know. Because the not operator always results in a Boolean value (True
or False
) this is trying to catch one of those values here, in this case False
. Since you can't throw True
or False
there's no use for this.
I think the intent of the author was something like this:
try:
raise ExampleError()
except ExampleError e:
throw e
except:
raise AnotherExampleError()