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:
1 | + | try: | |
2 | + | foo() | |
3 | + | except ValueError or TypeError: |
Catch multiple exception types using a tuple, not with or
operator.
- | except ValueError or TypeError: |
+ | except (ValueError, TypeError): |
4 | + | pass |