This document explains Python exception handling, including try, except, else and finally statements, with practical examples for robust error management and program control.
This document explores Python exception handling, focusing on the use of try, except, else, and finally statements to manage errors and control program flow. Readers will learn best practices for robust error management and maintaining program stability.
Exception handling in Python allows programs to respond gracefully to errors, preventing crashes and providing informative feedback to users.
The try block contains code that may raise an error. If an error occurs, control moves to the matching except block.
Example:
1try:
2 # Attempt to open and read a file
3 data = open('file.txt').read()
4except IOError:
5 print("Unable to open or read the data in the file.")
Multiple except blocks can be used to handle different error types. Avoid using a generic except without specifying the error type, as it can make debugging difficult.
Example:
1try:
2 # Some code
3except IOError:
4 print("IO error occurred.")
5except:
6 print("An unspecified error occurred.") # Not recommended
The else block executes if no exceptions are raised in the try block, providing confirmation of successful execution.
Example:
1try:
2 # Write to a file
3 file = open('file.txt', 'w')
4 file.write('Hello')
5except IOError:
6 print("Unable to write to the file.")
7else:
8 print("The file was written successfully.")
The finally block executes regardless of whether an exception occurred, often used for cleanup actions such as closing files.
Example:
1try:
2 file = open('file.txt', 'w')
3 file.write('Hello')
4except IOError:
5 print("Unable to write to the file.")
6else:
7 print("The file was written successfully.")
8finally:
9 file.close()
10 print("File is now closed.")
| Statement | Purpose |
|---|---|
| try | Run code that may raise an error |
| except | Handle specific errors |
| else | Run code if no errors occur |
| finally | Run code regardless of errors (cleanup) |
Exception handling is essential for writing robust Python programs. Using try, except, else, and finally statements ensures errors are managed gracefully, resources are cleaned up, and users receive clear feedback.
- Exception handling allows programs to respond to errors without crashing, providing informative feedback and maintaining stability.
- Generic except statements make debugging harder by hiding error details.
| Statement | Purpose |
|---|---|
| A. try | 1. Run code that may raise an error |
| B. except | 2. Handle specific errors |
| C. else | 3. Run code if no errors occur |
| D. finally | 4. Run code regardless of errors (cleanup) |
A-1, B-2, C-3, D-4.
The finally block in Python executes whether or not an exception occurs, making it ideal for cleanup actions like closing files.
True. The finally block always executes, ensuring resources are cleaned up.