Question
How can you catch multiple exceptions in one block?
Solution
β Verified
You can catch more than one type of error using a single except block by putting the exception names in round brackets.
Syntax:-
try:
# Code that may give different types of errors
except (ErrorType1, ErrorType2):
# This block will run if any of the errors happen
Example:--
try:
a = int("abc") # This gives ValueError
b = 10 / 0 # This gives ZeroDivisionError
except (ValueError, ZeroDivisionError):
print("An error occurred!")
Explanation:
- If any of the errors (ValueError or ZeroDivisionError) happens, the except block will run.
- This helps to handle multiple errors together without writing separate except blocks.
Click here to download practice questions on
Exception Handling in PythonMore Questions on Exception Handling in Python
Question 6
"Every syntax error is an exception but every exception cannot be a syntax error." Justify the statement.
View solution