Catching multiple exceptions in Python with a single except block
How can you catch multiple exceptions using a single except block?
We can catch multiple exceptions using a single "except" block by specifying multiple exception types inside parentheses. This allows us to handle different types of exceptions in the same block of code.
Here's the syntax:
try: # Code that may raise exceptions except (ExceptionType1, ExceptionType2, ...): # Code to handle exceptions of ExceptionType1 or ExceptionType2, etc.
In the above structure,
- try - Contains the code that may raise exceptions.
- except is followed by a tuple of exception types (ExceptionType1, ExceptionType2, etc.) enclosed in parentheses.
- The indented block following "except" is where we can put the code to handle exceptions of any of the specified types.
The following example illustrates how to catch multiple exceptions:
Code:
try:
n = int(input("Input a number: "))
result = 10 / n
except (ValueError, ZeroDivisionError):
print("Invalid input or division by zero occurred.")
Output:
Input a number: a Invalid input or division by zero occurred.
Input a number: 0 Invalid input or division by zero occurred.
In the above example, we catch both ValueError (if the user inputs something that cannot be converted to an integer, here n = 'a') and ZeroDivisionError (if the user enters zero, here n = 0) using a single except block.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-interview/how-can-you-catch-multiple-exceptions-using-a-single-except-block.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics