Lecture 02/27: CSC1302

Exception Handling in Python

  • 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

  1. Inside the function where the error occurs (h()).

  2. In the calling method (g()).

  3. In the outer caller (f()).

  • If not handled, it raises an error.

Exception Block Structure

  • 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.

Custom Exceptions

  • 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.

Modules in Python

  • 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.

Packages vs. Modules

  • 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.

Common Python Modules

  • Examples of Useful Modules

    • datetime, random, math, sys.

    • Reference additional examples in Ziboch, Chapter 11.

File Input/Output (I/O) Operations

  • 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:

      1. Open the file using open().

      2. Perform read/write operations.

      3. 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.

File Reading Techniques

  • 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.

Writing to Files

  • 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.

Using with Statement

  • Benefits of with

    • Automatically closes files once the block ends, preventing errors of forgetting to close files.

Upcoming Topics

  • Discuss command line arguments and their usage in the next session.

robot