Lesson 12: Python Exception Handling and Debugging | Coding Class Series
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 occursfinally→ 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
- Print statements – Track variable values and flow.
- Using IDE debugger – Step through code line by line.
- 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
- Write a program that asks for two numbers and divides them. Handle
ZeroDivisionErrorandValueError. - Open a file safely using
try-except-else-finally. - Raise a custom exception if a user enters a negative number.
- Implement logging to record all exceptions in your program.