Am I able to check for multiple error types with one try and except statement?


#1

Question

In Python, am I able to check for multiple error types with one try and except statement?

Answer

Yes, it is possible to check multiple error types with a single try and except statement.

For the except, we can include multiple error types listed within a tuple. It will check if any of the listed errors are encountered.

You can also do a general except without a specified error type, but that is not recommended as it will catch any errors, including ones we don’t want to check.

Example

# Multiple error types listed.
try:
  line of code
except(TypeError, NameError, ...):
  ...  

# Not recommended
try:
  line of code
except:
  ...