Overview of Exception Handling
Focus on handling exceptions across multiple methods (method chaining).
Identify responsible method for exception handling during errors in a chain of function calls.
Example Method Calls
Function f()
calls g()
, which calls h()
.
An error occurring in h()
needs to be handled.
Responsibility for Handling Exceptions
The responsibility can be assigned to any function in the call stack:
Handle it in h()
.
Delegate to g()
.
Delegate to f()
.
If no handling code exists, Python searches upward in the call stack.
Error Demonstration
Example: f(a, b)
where a
=1 and b
=0 results in a zero division error.
Three Options for Handling Exceptions
Inside the function where the error occurs (h()
).
In the calling method (g()
).
In the outer caller (f()
).
If not handled, it raises an error.
Try, Except, Finally Blocks
try
block: Executes code that may raise an exception.
except
block: Executes code to handle exceptions.
finally
block: Always executes, used for cleanup (e.g., closing files).
Use Case for finally
Important in file I/O operations to ensure files are always closed properly.
Creating a Custom Exception
Define a new class inheriting from Exception
.
Example: A custom exception for negative integers: LessThanZeroError
.
Raise this exception when a negative input is encountered.
Code Structure for Custom Exception
Ask user for input.
Raise LessThanZeroError
if input is negative.
Purpose of a Module
Avoid writing repetitive code by encapsulating commonly used functions in a single file.
Modules can be imported into scripts or other modules.
Importing Modules
To import a module named my_module.py
, use: import my_module
.
Python has a built-in variable sys.modules
to show loaded modules.
Using Functions from Modules
Use module_name.function_name()
to access specific functions.
Option to import specific functions: from my_module import function_name
.
Dependencies
A module required by another program is referred to as a dependency.
Python checks built-in modules first, then searches paths defined in sys.path
.
Reloading Modules
If changes to a module are made, use reload(module_name)
to update without restarting the program.
Concept of a Package
A package is a collection of related modules organized in directories.
Example structure:
game/
sound/
graphics/
Importing modules:
Import specific modules using the dot notation: import game.sound.music
.
Examples of Useful Modules
datetime
, random
, math
, sys
.
Reference additional examples in Ziboch, Chapter 11.
File System Structure
Types of file paths:
Absolute Path: Full path from root.
Example: /users/username/documents/file.txt
.
Relative Path: Path from the current directory.
Reading/Writing Files
General steps for file handling:
Open the file using open()
.
Perform read/write operations.
Close the file.
Opening Files
open(filename, mode)
:
Modes:
r
(read), w
(write), a
(append), etc.
Cursor Position
r
, w
, and r+
modes start at the file beginning.
a
mode starts at the end of the file.
Reading Methods
read(size)
: Reads a specified number of characters.
readlines()
: Reads all lines into a list.
String Handling
Use split()
to convert a string to a list of words.
Write Operations
write(content)
: Writes content—overwrites existing content in w
mode; adds in a
mode.
New Lines
Use \n
for new lines in text files.
with
StatementBenefits of with
Automatically closes files once the block ends, preventing errors of forgetting to close files.
Discuss command line arguments and their usage in the next session.