Published by Patrick Mutisya · 14 days ago
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. It is typically caused by an error condition that the program cannot handle automatically, such as trying to read a file that does not exist or dividing by zero.
| Exception Type | Cause | Typical Handling Strategy |
|---|---|---|
| FileNotFoundError | Attempt to open a file whose pathname does not exist. | Prompt user for a correct filename or create a new file. |
| IOError / EOFError | Read/write operation fails or reaches unexpected end of file. | Check file integrity, retry the operation, or abort gracefully. |
| PermissionError | Program lacks required read/write permissions. | Inform the user and request elevated privileges or alternative location. |
try statement.except clauses to catch specific exceptions.else clause that runs if no exception occurs.finally clause to release resources regardless of success or failure.try:
file = open('data.txt', 'r')
for line in file:
process(line)
except FileNotFoundError:
print('Error: data.txt was not found.')
except IOError as e:
print('I/O error:', e)
else:
print('File processed successfully.')
finally:
if 'file' in locals():
file.close()
| Aspect | Normal Flow | Exception Flow |
|---|---|---|
| Entry Point | Program reaches the statement directly. | An error is raised before the statement completes. |
| Control Transfer | Continues to the next sequential statement. | Control jumps to the matching except block. |
| Resource Management | Resources released at the end of the block. | finally ensures resources are released even after an exception. |
When the built‑in exception types are not descriptive enough, you can define your own exception class.
class InvalidRecordError(Exception):
"""Raised when a record in a data file does not meet validation rules."""
pass
# Usage
if not validate(record):
raise InvalidRecordError('Record format is incorrect')
except: unless re‑raising.finally block or use a context manager.Exception handling transforms unpredictable runtime errors into manageable events, allowing programs that work with files to remain robust, maintainable, and user‑oriented.