Unit 7 • Lesson 7

Understanding Errors and Exceptions

Overview

Errors occur when something goes wrong, such as dividing by zero or accessing a missing file. You'll understand the difference between syntax and runtime errors and how exceptions help Python handle unexpected situations, making your programs more robust.

Beginner 20–25 min

What You Will Learn in This Lesson

By the end of this lesson, you will know:

  • What errors are: Understand when and why errors occur in Python.
  • Types of errors: Learn about syntax errors vs runtime errors (exceptions).
  • Common exceptions: Recognize common error types like FileNotFoundError, ValueError, etc.
  • Error messages: Learn to read and understand Python error messages.
  • Why exceptions exist: Understand how exceptions help make programs more robust.

What Are Errors?

An error occurs when something goes wrong in your program. Python stops executing and shows you an error message explaining what happened.

Example: A Simple Error
result = 10 / 0
# ZeroDivisionError: division by zero

Why Errors Happen

  • Invalid operations (like dividing by zero)
  • Missing files or resources
  • Wrong data types
  • Typos or syntax mistakes
  • Accessing things that don't exist

Two Types of Errors

Python has two main categories of errors:

Syntax Errors

Mistakes in your code's grammar. Python can't even run the program.

# Missing colon
if x == 5
    print(x)

# SyntaxError: expected ':'

Runtime Errors (Exceptions)

Errors that happen while the program is running. The code syntax is correct, but something goes wrong.

# Code is correct, but file doesn't exist
file = open("missing.txt", "r")

# FileNotFoundError: [Errno 2] No such file

Key Difference

Syntax errors prevent your program from running at all. Exceptions occur while your program is running and can be handled.

Common Exceptions

Here are some common exceptions you'll encounter:

Exception When It Occurs Example
FileNotFoundError File doesn't exist open("missing.txt", "r")
ValueError Wrong value type int("abc")
ZeroDivisionError Dividing by zero 10 / 0
IndexError List index out of range my_list[10] (list has 5 items)
KeyError Dictionary key doesn't exist my_dict["missing"]
TypeError Wrong data type for operation "hello" + 5

Reading Error Messages

Python error messages tell you exactly what went wrong. Let's learn to read them:

Example Error Message
Traceback (most recent call last):
  File "example.py", line 3, in <module>
    result = 10 / 0
ZeroDivisionError: division by zero

Understanding the Message

  1. Traceback: Shows where the error occurred
  2. File and line: Tells you the file name and line number
  3. Error type: The type of exception (ZeroDivisionError)
  4. Error message: Description of what went wrong

File-Related Exceptions

When working with files, you'll encounter specific exceptions:

FileNotFoundError
file = open("nonexistent.txt", "r")
# FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent.txt'
PermissionError
# Trying to write to a read-only file
file = open("/readonly/file.txt", "w")
# PermissionError: [Errno 13] Permission denied

Note: These exceptions can be handled with try and except blocks, which we'll learn in the next lesson!

Practice: Understanding Errors

Try It Yourself

Try creating different types of errors to see what happens:

Click "Run Code" to see your output here

Try it: Uncomment different lines to see different error messages. Notice how Python tells you exactly what went wrong!

Understanding Tracebacks

A traceback shows the sequence of function calls that led to an error:

Example Traceback
Traceback (most recent call last):
  File "example.py", line 10, in <module>
    result = divide_numbers(10, 0)
  File "example.py", line 5, in divide_numbers
    return a / b
ZeroDivisionError: division by zero

Reading Tracebacks

To read a traceback effectively:

  1. Start at the bottom: The last line shows the exception type and message
  2. Read upwards: Each line shows where the code was called from
  3. Find your code: Look for your own files (not Python's internal files)
  4. Check line numbers: The line number tells you exactly where the error occurred
Example: Nested Function Calls
def read_config():
    return open("config.txt", "r").read()

def process_config():
    config = read_config()
    return config.upper()

def main():
    result = process_config()
    print(result)

main()
# If config.txt doesn't exist, traceback shows:
# - main() called process_config()
# - process_config() called read_config()
# - read_config() tried to open file → FileNotFoundError

Why Exceptions Are Useful

Exceptions might seem annoying, but they're actually helpful:

1

Early Detection

They catch problems immediately, before they cause worse issues. Better to fail fast than produce incorrect results!

2

Clear Messages

They tell you exactly what went wrong and where. The traceback points you to the exact line of code.

3

Handling

You can catch and handle exceptions to make your program more robust. Programs don't have to crash!

4

Debugging

Exceptions help you find bugs quickly. The error message and traceback give you clues about what went wrong.

Think of Exceptions as Safety Nets

Exceptions prevent your program from continuing with bad data or invalid operations. They force you to handle edge cases and make your code more reliable.

Summary

In this lesson, you learned:

  • Errors: Occur when something goes wrong in your program
  • Syntax errors: Prevent the program from running (grammar mistakes)
  • Exceptions: Runtime errors that occur while the program runs
  • Common exceptions: FileNotFoundError, ValueError, ZeroDivisionError, etc.
  • Error messages: Tell you what went wrong and where
  • Useful: Exceptions help catch problems early and can be handled

Next Step

In the next lesson, you'll learn how to handle exceptions gracefully using try and except blocks!

End-of-Lesson Exercises

Think about these questions to reinforce what you've learned:

Exercise 1: Error Types

What's the difference between a syntax error and an exception? Give an example of each.

Exercise 2: Common Exceptions

Name three common exceptions you might encounter when working with files, and explain when each occurs.