Showing posts with label Python logging. Show all posts
Showing posts with label Python logging. Show all posts

Monday, March 16, 2026

Lesson 12: Python Exception Handling and Debugging | Coding Class Series

March 16, 2026 0



Lesson 12: Python Exception Handling and Debugging | Coding Class Series

Introduction

Welcome to Lesson 12!
In this lesson, we will learn how to handle errors in Python using exceptions and use debugging techniques to make our programs more robust and error-free. Exception handling ensures that your program does not crash unexpectedly.


1. What is an Exception?

An exception is an error that occurs during program execution.
Examples: ZeroDivisionError, FileNotFoundError, ValueError.

# Example: Division by zero
a = 10
b = 0
print(a / b)  # This will cause ZeroDivisionError

2. Using try and except

The try block contains code that might raise an exception.
The except block handles the exception gracefully.

try:
    a = 10
    b = 0
    result = a / b
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")

3. Handling Multiple Exceptions

You can catch multiple types of exceptions:

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Error: Division by zero!")
except ValueError:
    print("Error: Invalid input, not a number!")

4. Using else and finally

  • else → Executes if no exception occurs
  • finally → Executes always, even if an exception occurs
try:
    file = open("example.txt", "r")
except FileNotFoundError:
    print("File not found!")
else:
    print(file.read())
finally:
    print("Execution finished.")

5. Raising Exceptions

You can raise your own exceptions using raise:

age = int(input("Enter your age: "))
if age < 18:
    raise ValueError("You must be 18 or older to proceed.")

6. Debugging Techniques

  1. Print statements – Track variable values and flow.
  2. Using IDE debugger – Step through code line by line.
  3. Logging module – Log errors for later analysis.
import logging

logging.basicConfig(filename="app.log", level=logging.ERROR)

try:
    x = 10 / 0
except ZeroDivisionError as e:
    logging.error("An error occurred: %s", e)

7. Practice Exercises

  1. Write a program that asks for two numbers and divides them. Handle ZeroDivisionError and ValueError.
  2. Open a file safely using try-except-else-finally.
  3. Raise a custom exception if a user enters a negative number.
  4. Implement logging to record all exceptions in your program.