8 2 Handling Multiple Exceptions Explained
Key Concepts
Handling multiple exceptions in Python involves several key concepts:
- Using multiple
except
blocks - Handling multiple exceptions in a single
except
block - Using
else
andfinally
blocks - Raising custom exceptions
1. Using Multiple except
Blocks
You can handle different types of exceptions by using multiple except
blocks. Each except
block can handle a specific type of exception.
Example:
try: num = int(input("Enter a number: ")) result = 10 / num except ValueError: print("Invalid input. Please enter a number.") except ZeroDivisionError: print("Cannot divide by zero.")
Analogy: Think of multiple except
blocks as having different specialists to handle different types of issues.
2. Handling Multiple Exceptions in a Single except
Block
You can handle multiple exceptions in a single except
block by specifying a tuple of exception types.
Example:
try: num = int(input("Enter a number: ")) result = 10 / num except (ValueError, ZeroDivisionError): print("An error occurred. Please enter a valid number.")
Analogy: Think of a single except
block handling multiple exceptions as a generalist who can handle various issues.
3. Using else
and finally
Blocks
The else
block is executed if no exceptions occur, and the finally
block is always executed, regardless of whether an exception occurred.
Example:
try: num = int(input("Enter a number: ")) result = 10 / num except (ValueError, ZeroDivisionError): print("An error occurred. Please enter a valid number.") else: print("The result is:", result) finally: print("Execution completed.")
Analogy: Think of the else
block as a celebration for a successful task, and the finally
block as a cleanup step after the task is done.
4. Raising Custom Exceptions
You can raise custom exceptions to handle specific scenarios in your code. This allows for more precise error handling.
Example:
class CustomError(Exception): pass try: num = int(input("Enter a number: ")) if num < 0: raise CustomError("Negative numbers are not allowed.") result = 10 / num except (ValueError, ZeroDivisionError): print("An error occurred. Please enter a valid number.") except CustomError as ce: print(ce)
Analogy: Think of raising custom exceptions as creating a personalized error message for a specific situation.
Putting It All Together
By understanding and using these concepts effectively, you can handle multiple exceptions in Python, making your code more robust and user-friendly.
Example:
try: num = int(input("Enter a number: ")) if num < 0: raise CustomError("Negative numbers are not allowed.") result = 10 / num except (ValueError, ZeroDivisionError): print("An error occurred. Please enter a valid number.") except CustomError as ce: print(ce) else: print("The result is:", result) finally: print("Execution completed.")