Exception handling in Python allows you to manage errors and exceptional events gracefully. By using try-except blocks, you can ensure your program doesn't crash unexpectedly and can handle errors appropriately.
Why Exception Handling?
- Graceful Degradation: Prevents the program from terminating unexpectedly.
- Resource Management: Ensures resources are properly released (e.g., closing files, database connections).
- User Feedback: Provides informative messages to users when something goes wrong.
Basic Exception Handling
Here's a basic example of handling a FileNotFoundError when trying to open a missing file:
try: myFile = open("missing.txt") # Read in the 1st line only oneLine = myFile.readline() print("You have one chance to impress: ", oneLine) myFile.close() except FileNotFoundError as fnfe: print("The file you attempted to open isn't present, blockhead!") print("By the way, the error information is: ", fnfe, "(blockhead..)") |
Explanation:
- Try Block: Contains the code that might raise an exception.
- Except Block: Handles specific exceptions. In this case, FileNotFoundError.
- Error Object: The as keyword assigns the exception object to a variable (fnfe) for further inspection.
Finally Block
The finally block allows you to execute code whether or not an exception occurred. This is useful for cleanup actions like closing files or releasing resources.
try: myFile = open("missing.txt") # Read in the 1st line only oneLine = myFile.readline() print("You have one chance to impress: ", oneLine) myFile.close() except FileNotFoundError as fnfe: print("The file you attempted to open isn't present, blockhead!") print("By the way, the error information is: ", fnfe, "(blockhead..)") finally: print("You should perform any tasks that must be completed even if the try block abnormally ends here in the finally block...blockhead") |
Using with Statement
The with statement simplifies resource management by ensuring resources are automatically cleaned up. For file handling, it means you don't need to explicitly close the file.
with open("amateurlyrics.txt") as myFile: # Read in the 1st line only oneLine = myFile.readline() print("You have one chance to impress: ", oneLine) |
Custom Exceptions
You can define your own exceptions by creating a new exception class. This is useful for handling specific errors in your application.
class MyException(Exception): def __init__(self): print("A new object of type MyException") # Raising a custom exception raise MyException |
Explanation:
- Custom Exception Class: MyException extends the base Exception class.
- Raising the Exception: The raise keyword is used to trigger the exception.
Example Scenario: File Handling with Proper Cleanup
This example demonstrates how to handle file operations in Python with proper exception handling and cleanup. It uses the try-except-finally blocks along with the with statement for resource management.
try: with open("example.txt", "r") as file: content = file.read() print(content) except FileNotFoundError as e: print("File not found:", e) finally: print("Finished attempting to read the file.") |
Explanation:
- with Statement: Automatically handles closing the file, reducing the risk of resource leaks.
- Specific Exception Handling: The except FileNotFoundError block handles the specific case where the file is not found, providing a clear error message.
- Cleanup with finally: Ensures that the cleanup code is executed regardless of the outcome of the try block.
Example of Handling Multiple Specific Exceptions
Here's how you can handle multiple specific exceptions within a single try block:
try: with open("example.txt", "r") as file: content = file.read() print(content) except FileNotFoundError as e: print("File not found:", e) except IOError as e: print("IO error occurred:", e) finally: print("Finished attempting to read the file.") |