Debugging and Error Handling

Programming can be a bit like solving a puzzle—sometimes things don’t work as expected! In this lesson, you’ll learn how to identify, understand, and fix errors in your code. You’ll also discover strategies to handle errors gracefully.


Objectives

By the end of this lesson, you will:

  • Understand the types of errors that can occur in programs.
  • Learn debugging techniques to identify and fix issues.
  • Use error-handling methods to make your code more robust.

1. Types of Errors

Errors come in different forms, and knowing how to spot them is key to fixing them. Here are the most common types:

1.1 Syntax Errors

  • What are they?
    Syntax errors occur when your code breaks the rules of the programming language.
  • Example:
    print("Hello, World!  # Missing closing quote
    
  • Fix:
    Check for typos, unmatched brackets, or missing punctuation.

1.2 Runtime Errors

  • What are they?
    These errors happen while your program is running and usually occur due to unexpected situations, like dividing by zero or accessing an invalid index.
  • Example:
    numbers = [1, 2, 3]
    print(numbers[5])  # Index out of range
    
  • Fix:
    Use tools like print statements or debuggers to locate the problem.

1.3 Logic Errors

  • What are they?
    Your program runs, but it doesn’t do what you expect because of incorrect logic.
  • Example:
    total = 10
    total = total * 2  # Meant to add 2, but multiplied instead
    
  • Fix:
    Test your code with sample inputs and verify the outputs.

2. Debugging Techniques

Debugging is the process of finding and fixing errors. Here are some useful techniques:

2.1 Print Statements

  • Insert print() statements in your code to see what’s happening at each step.
  • Example:

    def add_numbers(a, b):
        print(f"Adding {a} and {b}")
        return a + b
    
    result = add_numbers(3, 4)
    print(f"Result: {result}")
    

2.2 Rubber Duck Debugging

  • Explain your code step-by-step to a rubber duck (or any object).
    This helps you notice mistakes by thinking aloud!

2.3 Debugging Tools

  • Use built-in debugging tools in IDEs (e.g., breakpoints and step-through debugging).

2.4 Test Small Parts

  • Break your code into smaller chunks and test each part independently. See our post on Unit Tests for more on this approach.

3. Error Handling

Sometimes errors are unavoidable. Here’s how you can handle them gracefully:

3.1 Try-Except Blocks

In many programming languages, you can use try and except (or similar) blocks to catch errors and prevent your program from crashing.

  • Example (Python):
    try:
        number = int(input("Enter a number: "))
        print(f"You entered: {number}")
    except ValueError:
        print("That’s not a valid number!")
    

3.2 Defensive Programming

  • Anticipate potential issues and write code to handle them.
  • Example: Check user input before performing operations:
    age = input("Enter your age: ")
    if age.isdigit():
        print(f"You are {age} years old!")
    else:
        print("Please enter a valid age.")
    

4. Debugging Practice

Activity 1: Spot the Bug

Here’s a program with an error. Can you find and fix it?

def divide_numbers(a, b):
    return a / b

result = divide_numbers(10, 0)
print(f"The result is: {result}")

Hint: What happens when you divide by zero?


Activity 2: Debugging Challenge

Try running this code and fixing all the errors:

name = input("What is your name? ")
print("Hello, " + Name)  # Error: Name is not defined
if len(name > 0):  # Error: Incorrect parentheses
    print("Nice to meet you!")
else
    print("You didn't enter a name.")  # Error: Missing colon

Summary

Debugging and error handling are essential skills for every programmer. By understanding errors and practicing debugging techniques, you’ll become more confident in solving problems and writing error-free code.


Homework

  1. Debug the following code and fix the errors:

    def greet(name)
        print("Hello, " + name)
    greet("Alice")
    
  2. Write a program that asks the user for a number and handles invalid input gracefully.

  3. Research a debugging tool for your chosen programming language and try using it on a small project.


Happy debugging!