Showing posts with label Python debugging. Show all posts
Showing posts with label Python debugging. 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.


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

March 16, 2026 0



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

Introduction

Welcome to Lesson 15!
In this lesson, we will learn how to handle errors in Python programs using exceptions and debug our code.
Exception handling is important to prevent program crashes and manage unexpected situations gracefully.


1. What is an Exception?

An exception is an error that occurs during the execution of a program.
Common examples:

  • Division by zero
  • File not found
  • Index out of range
# Division by zero
a = 10
b = 0
print(a / b)  # Raises ZeroDivisionError

2. Try and Except

Use try and except to catch and handle exceptions.

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

3. Handling Multiple Exceptions

You can handle different types of exceptions separately.

try:
    numbers = [1, 2, 3]
    print(numbers[5])
    a = 10 / 0
except IndexError:
    print("Index not found in the list!")
except ZeroDivisionError:
    print("Cannot divide by zero!")

4. Using else and finally

  • else: runs if no exception occurs
  • finally: always runs, even if an exception occurs
try:
    a = 10
    b = 2
    print(a / b)
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")
else:
    print("Division successful!")
finally:
    print("This runs always!")

5. Raising Exceptions

You can manually raise exceptions using raise.

age = -5

if age < 0:
    raise ValueError("Age cannot be negative!")

6. Debugging Tips

  • Print statements: Check the values of variables at different points.
  • Python debugger (pdb): Step through code line by line.
  • IDE debugging tools: PyCharm, VS Code allow breakpoints and watches.
import pdb

x = 5
y = 0

pdb.set_trace()  # Start debugging here
z = x / y
print(z)

7. Practice Exercises

  1. Write a program that asks the user for two numbers and divides them. Handle division by zero errors.
  2. Open a file that may not exist and handle FileNotFoundError.
  3. Raise an exception if a user's input string length is less than 5.
  4. Use pdb to debug a program that calculates the factorial of a number.


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.