Catching Multiple Exceptions in One Line with Python's Except Block
In Python, you can capture a variety of exceptions using the 'except' block. Traditionally, handling multiple exceptions involved using several individual 'except' clauses:
try: # Code that may fail except IDontLikeYouException: # Handle IDontLikeYouException except YouAreTooShortException: # Handle YouAreTooShortException
However, if you need to handle the same exception in response to multiple other exceptions, a more concise approach exists.
Catching Multiple Exceptions with a Tuple
By grouping exceptions into a tuple, you can handle their occurrences in a single 'except' block:
try: # Code that may fail except (IDontLikeYouException, YouAreBeingMeanException) as e: # Handle both exceptions
In this code, the tuple '(IDontLikeYouException, YouAreBeingMeanException)' specifies that the 'except' block will execute if either of those exceptions is raised.
Example Usage
Consider the code below:
def say_please(): print("Please...") try: raise IDontLikeYouException() except (IDontLikeYouException, YouAreBeingMeanException): say_please()
When the 'say_please()' function is called in the 'except' block, it prints "Please...". This demonstrates how handling multiple exceptions using a tuple simplifies exception handling.
Note for Python 2
In Python 2, you can optionally include a variable name after the closing parenthesis of the tuple, but it is not required and deprecated in Python 3. Instead, use 'as' to bind the exception object to a variable:
try: # Code that may fail except (IDontLikeYouException, YouAreBeingMeanException) as e: # Handle both exceptions
The above is the detailed content of How Can I Catch Multiple Exceptions in a Single Python `except` Block?. For more information, please follow other related articles on the PHP Chinese website!