How do you catch multiple different exceptions in Python and handle each of them differently?
Experience Level: Junior
Tags: Python
Answer
Use try/except block. In the except block define the type of exception that you want to catch. Use one except block for handling one exception. Sort the except blocks from the most specific at the top to the most generic at the bottom.
Example:
def my_method():
try:
int("This will cause exception to be raised")
except ValueException:
print("Your value is not a number.")
except Exception:
print("Something went seriously wrong.")
Related Python job interview questions
How do you use PIP?
Python JuniorWhat is Python PIP?
Python JuniorHow do you catch one specific exception in Python?
Python JuniorWhat does **kwargs mean in Python?
Python JuniorWhat does *args mean in Python?
Python Junior