Finding and Fixing Errors
Bugs are Essential Clues
In programming, errors (often called bugs) are not failures—they are essential clues. Even senior developers spend a significant portion of their time debugging.
This lesson will teach you how to read Python's diagnostic reports and handle errors gracefully so your programs don't crash unexpectedly.
Welcome to the world of debugging. In programming, we call errors 'bugs'. Instead of seeing them as failures, think of them as essential clues left by Python to help you improve your code. Even the most experienced developers spend hours every day hunting down these little issues.
- Errors are a natural part of the development process.
- Debugging is the skill of identifying and fixing these issues.
- Python provides detailed reports to help you find the problem.
The Three Types of Errors
Not all errors are the same. Understanding the category of error helps you know where to start looking.
- Syntax Errors: Grammar mistakes.
- Runtime Errors: Crashes during execution.
- Logical Errors: Wrong output, no crash.
There are three main categories of errors you'll encounter. Click each one to see what they look like in action. Syntax errors are like grammar mistakes. If you forget a colon or a parenthesis, Python can't even begin to run your code. Logical errors are the trickiest. The code runs perfectly and doesn't crash, but the result is wrong—like using a plus sign when you meant to multiply. Runtime errors, or Exceptions, happen while the code is running. Your code 'grammar' is perfect, but you asked Python to do something impossible, like dividing by zero.
- Syntax errors stop the program before it even starts.
- Runtime errors (Exceptions) occur while the code is running.
- Logical errors are the hardest to find because there is no error message.
Decoding the Traceback
When a runtime error occurs, Python prints a traceback. To solve the mystery, always read it from the bottom up!
When your code crashes, Python gives you a traceback report. It looks like a lot of red text, but don't panic! The secret is to read it from the bottom up. The very last line tells you exactly what went wrong. The line just above that tells you exactly where it happened.
- The bottom line tells you WHAT happened.
- The line above it tells you WHERE it happened.
- Reading top-down is often confusing for beginners; start at the end.
Interactive Debugging Lab
This script is supposed to calculate a discount, but it has two bugs. Find and fix them to make it work!
Exactly! 'discunt' was a typo. Fixing that to 'discount' resolves the Name Error. Let's put your skills to the test. This code for a discount calculator is broken. Look at the code and click on the lines that need fixing. Well done! The code now runs perfectly and returns the correct discount. You've successfully debugged your first script! Great catch! You added the missing colon to the function definition. That fixes the Syntax Error.
- Identify missing syntax (the colon).
- Identify naming errors (misspelled variable).
Error Handling: The Safety Net
We use try and except blocks to provide a 'Plan B' for your code. This prevents the program from crashing when something predictable goes wrong.
Sometimes you know an error might happen, like when a user enters text instead of a number. Instead of letting the program crash, we use a 'try' block to attempt the action, and an 'except' block as a safety net to handle the problem gracefully.
- The 'try' block contains code that might fail.
- The 'except' block contains the code to run if a failure occurs.
- This allows the rest of the program to continue running.
Socratic Debugging Session
A student wrote a program to divide two numbers, but it keeps crashing when the second number is zero. Chat with your AI mentor to figure out how to fix it with try/except.
I'm here to help you master error handling. I have a script that crashes when I divide by zero. How do you think we should fix it using 'try' and 'except'?
- Practice explaining error handling concepts.
- Identify the correct exception type for division by zero.
Specific vs. Bare Except
A common pitfall is using a bare except (writing except: without a type). This can hide serious bugs you didn't mean to ignore!
In the world of error handling, precision is key. Using a 'bare except' is like wearing a blindfold; it catches every error but hides the truth. Always aim to catch specific exceptions so you know exactly what went wrong.
- Always try to catch specific errors like ValueError or ZeroDivisionError.
- A bare except catches EVERYTHING, including system exits and keyboard interrupts.
- Specific catching makes your code easier to debug later.
Final Challenge: Build a Safe Calculator
Write a small code snippet that asks for a number and divides 100 by it. Use try and except to handle cases where the user enters 0 or text.
For your final challenge, write a short program that handles errors for a division task. Use a try-except block to catch both ZeroDivisionError and ValueError.
- Implement multi-exception handling.
- Use appropriate input conversion.