To handle multiple exceptions using a single except
block in Python, you can specify a tuple of exception types after the except
keyword. Here’s an example:
# some code that might raise an exception
pass
except (TypeError, ValueError, ZeroDivisionError) as e:
# handle the exception
print(“Caught an exception:”, e)
In the example above, we use a single except
block to catch three different types of exceptions: TypeError
, ValueError
, and ZeroDivisionError
. If any of these exceptions are raised within the try
block, the except
block will be executed and the exception object will be assigned to the variable e
.
You can also use a single except
block to catch all exceptions by specifying the base class Exception
, like this:
# some code that might raise an exception
pass
except Exception as e:
# handle the exception
print(“Caught an exception:”, e)
This will catch all exceptions, including built-in exceptions like TypeError
and ValueError
, as well as custom exceptions that inherit from the Exception
class. However, it’s generally better to catch specific exceptions whenever possible, so that you can handle them appropriately and avoid catching unexpected exceptions that might indicate a bug in your code.
- sunny asked 1 month ago
- You must login to post comments
Please login first to submit.