Lesson 15: Python Exception Handling and Debugging | Coding Class Series
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 occursfinally: 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
- Write a program that asks the user for two numbers and divides them. Handle division by zero errors.
- Open a file that may not exist and handle
FileNotFoundError. - Raise an exception if a user's input string length is less than 5.
- Use
pdbto debug a program that calculates the factorial of a number.