Showing posts with label Python lesson 18. Show all posts
Showing posts with label Python lesson 18. Show all posts

Monday, March 16, 2026

Lesson 18: Python Error Handling, Exceptions, and Debugging | Coding Class Series

March 16, 2026 0

 


Lesson 18: Python Error Handling, Exceptions, and Debugging | Coding Class Series

Introduction

Welcome to Lesson 18!
In this lesson, we will learn about handling errors in Python, using exceptions, and debugging techniques.
Error handling ensures that your program does not crash unexpectedly and behaves predictably.


1. Common Errors in Python

  • SyntaxError – Mistake in code structure
  • NameError – Using a variable before defining it
  • TypeError – Using incompatible data types
  • ValueError – Wrong type of value for a function
  • ZeroDivisionError – Dividing a number by zero

Example:

# SyntaxError example
# print("Hello World"

# NameError example
# print(x)

2. Handling Exceptions with try-except

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

3. Using else and finally

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except Exception as e:
    print("Error occurred:", e)
else:
    print("Division successful! Result is", result)
finally:
    print("This block always executes")

4. Raising Custom Exceptions

def check_age(age):
    if age < 18:
        raise ValueError("Age must be at least 18")
    else:
        print("Access granted")

try:
    check_age(15)
except ValueError as e:
    print("Error:", e)

5. Debugging Techniques

  • Use print statements to check variable values
  • Use Python debugger (pdb) for step-by-step execution:
import pdb

def add(a, b):
    pdb.set_trace()
    return a + b

result = add(5, "10")  # This will raise TypeError
print(result)
  • Use IDE debugging tools (VS Code, PyCharm)

6. Practice Exercises

  1. Write a program that divides two numbers and handles all possible exceptions.
  2. Create a function to calculate square root, raise a custom exception if the number is negative.
  3. Debug a program that adds a string to a number and fix it using try-except.
  4. Use finally to close a file after reading its contents, even if an error occurs.