Student Activity

Student Activity Guide:

1) Understanding Exceptions in Python

  • Learn about different types of exceptions such as ZeroDivisionError, ValueError, and TypeError.

  • Identify and debug errors in Python programs.

Example Code:

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")

Student Exercise: Try causing and handling a ValueError by converting a non-numeric string to an integer.

2) Handling Errors with Try-Except Blocks

  • Implement error handling using try, except, else, and finally.

  • Ensure program stability by catching unexpected errors.

Example Code:

try:
    num = int(input("Enter a number: "))
    print(f"You entered: {num}")
except ValueError:
    print("Invalid input! Please enter a number.")
finally:
    print("Execution completed.")

Student Exercise: Write a program that catches multiple exception types, such as IndexError and KeyError.

3) Raising Custom Exceptions

  • Define custom exceptions using raise.

  • Create specific error messages to guide users.

Example Code:

Student Exercise: Create a function that raises an exception if an input number is negative.

4) Debugging and Logging in Python

  • Use logging for better debugging and tracking errors.

  • Understand different logging levels (DEBUG, INFO, WARNING, ERROR, CRITICAL).

Example Code:

Student Exercise: Modify the logging configuration to write logs to a file and test different logging levels.

Final Activity

  • Create a Python program that reads a file, handles errors, and logs exceptions to a file.

Last updated