Recently I met an example of code I've never seen before:
try:
# a simple bunch of code
if sample == 0:
return True
else:
raise ExampleError()
except not ExampleError:
raise AnotherExampleError()
How does it work (if it works at all)?
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.
Try Except in Python The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block.
By using an except block, you tell the program what to do in the event of a KeyError (here, assign result_dict[value] = 1 if it doesn't exist), and then the program continues. Basically, you're avoiding a crash.
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()
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.
A quick test shows that the code will throw a TypeError if it reaches that line:
try:
raise BaseException
except not BaseException:
print("Test1")
except BaseException:
print("Test2")
Exception:
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "main.py", line 3, in except not BaseException: TypeError: catching classes that do not inherit from BaseException is not allowed
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