In Python, we often encounter situations where we need to handle multiple exceptions within our code. To achieve this, we can use the try-except
statement with multiple except
blocks. This allows us to catch and handle different types of exceptions separately, providing flexibility and improving the robustness of our code.
Here’s the basic syntax of the try-except
statement with multiple except
blocks in Python:
try:
# code that may potentially raise exceptions
except ExceptionType1:
# code to handle exceptions of type ExceptionType1
except ExceptionType2:
# code to handle exceptions of type ExceptionType2
...
except ExceptionTypeN:
# code to handle exceptions of type ExceptionTypeN
else:
# code to execute if no exceptions were raised
finally:
# code to execute regardless of whether an exception was raised or not
Let’s look at a more practical example to see how multiple except
blocks can be utilized effectively. Suppose we have a function that performs division and returns the result:
def divide(a, b):
try:
result = a / b
print("Division result:", result)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input!")
except Exception as e:
print("An error occurred:", str(e))
else:
print("Division completed successfully!")
finally:
print("Executing finally block.")
# Example usage
divide(10, 2) # Division result: 5.0 | Division completed successfully! | Executing finally block.
divide(10, 0) # Cannot divide by zero! | Executing finally block.
divide(10, "two") # Invalid input! | Executing finally block.
In this example, we have three except
blocks that catch and handle different types of exceptions. If a ZeroDivisionError
occurs, we print an appropriate message. If a ValueError
occurs, we handle it differently. If any other exception occurs, it will be caught by the last except
block.
The else
block is executed only when no exceptions are raised, indicating that the division was successful. The finally
block is executed regardless of whether an exception was raised or not. This block is typically used for cleanup operations, such as closing files or releasing resources.
Using multiple except
blocks allows us to handle specific exceptions separately while providing a fallback option for any unexpected exceptions.
So, the next time you need to handle multiple exceptions in your Python code, remember to leverage the try-except
statement with multiple except
blocks for more efficient and structured exception handling.