Incorrectly using or in exception handling

Catch multiple exception types using a tuple, not with or operator.

Using or in exception handler is valid Python insofar as the python parser does not complain, but using or to specify multiple exception classes does not do what you think it should. Take this code as example:

This will only catch ValueError. TypeError will not be caught because Python is treating the ValueError or TypeError as a binary comparison to evaluate rather than as a list of exception classes to catch. Python evaluates ValueError or TypeError to ValueError because ValueError is truthy.

To have Python catch multiple exception types instead specify the multiple types as a tuple:

If our GitHub code review bot spots this issue in your pull request it gives this advice:

code-review-doctorbotsuggested changes just now
helpers.py
1
+
try:
2
+
    foo()
3
+
except ValueError or TypeError:

Catch multiple exception types using a tuple, not with or operator.

Read more
Suggested changes
-
except ValueError or TypeError:
+
except (ValueError, TypeError):
Commit suggestion
4
+
    pass
Update helpers.py

Instantly check if you have this issue for free

    Works with tools you use

    Read about how it works.