⚠️ Exception Handling in Python
Description: Understand how to manage errors gracefully in Python programs using structured exception handling.
1. Handling Multiple Exceptions
Python allows handling multiple exceptions using multiple except blocks or a single except block with a tuple of exceptions.
Explanation: This code prompts the user to enter a number and attempts to divide 10 by that number. It handles two specific exceptions: ValueError if the input is not a number, and ZeroDivisionError if the input is zero. If no exception occurs, it prints the result.
2. Using finally for Cleanup
The finally block is executed regardless of whether an exception occurs, making it ideal for cleanup actions.
Explanation: This code attempts to open and read a file. If the file is not found, it catches the FileNotFoundError. Regardless of the outcome, the finally block ensures that the file is closed properly.
3. Raising Exceptions Manually
You can raise exceptions manually using the raise statement to enforce certain conditions.
Explanation: This code prompts the user to enter their age. If the entered age is negative, it raises a ValueError to indicate invalid input.
4. Creating Custom Exceptions
Custom exceptions can be created by defining a new class that inherits from the built-in Exception class.
Explanation: This code defines a custom exception NegativeAgeError and raises it if the user enters a negative age. The exception is then caught and handled appropriately.
5. Nested try-except Blocks
Python allows nesting of try-except blocks to handle exceptions at different levels of code execution.
Explanation: This code demonstrates nested try-except blocks, where the inner block handles division by zero, and the outer block handles invalid input.
6. Using else with try-except
The else block can be used to execute code if no exceptions are raised in the try block.
Explanation: If no exception occurs in the try block, the else block will execute. This is useful for separating error-handling logic from the main logic.
7. Handling Multiple Exceptions in One Line
You can also handle different exceptions using a single except block with a tuple.
Explanation: This code catches both ValueError and ZeroDivisionError using one except block, and prints the error message accordingly.
8. Try-Except Inside a Function
Exception handling can be integrated inside functions to create more robust programs.
Explanation: This function handles division and protects against division by zero using a try-except block inside a function.
9. Using Assertions with Exception Handling
Assertions can be used to enforce conditions and raise exceptions if conditions are false.
Explanation: The assert statement checks if the condition is true. If not, it raises an AssertionError. Here, it's used to ensure age is not negative.
10. Logging Exceptions
You can use the logging module instead of print() to keep track of errors.
Explanation: The logging module provides a way to log error messages, which is more flexible and robust than printing to the console, especially for large applications.
Summary:
- try-except helps catch and handle errors.
- finally always runs, great for cleanup.
- raise is used to manually trigger errors.
- Custom exceptions make error handling more descriptive.
- Assertions are useful for debugging.