No program is perfect. Errors are a natural part of programming, especially when dealing with user input, files, APIs, or external systems.
In this lesson, you will learn how to:
✔ Handle errors gracefully using try/except
✔ Use else and finally blocks
✔ Raise your own exceptions
✔ Debug Python programs
✔ Use logging for professional error tracking
These skills are essential for building robust, reliable, and production-ready applications.
An exception is an error that occurs during program execution.
print(10 / 0) # ZeroDivisionErrorPrevent crashes by handling errors:
try:
x = int(input("Enter a number: "))
print(10 / x)
except:
print("An error occurred!")try:
x = int(input("Enter a number: "))
print(10 / x)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input!")
✔ Best practice: always catch specific exceptions.
else (runs if no error)try:
x = int(input())
except ValueError:
print("Error")
else:
print("Valid number:", x)
finally (always runs)try:
f = open("file.txt")
except:
print("Error opening file")
finally:
print("This always runs")You can create your own errors using raise.
age = int(input("Enter age: "))
if age < 0:
raise ValueError("Age cannot be negative")You can define your own exception classes.
class CustomError(Exception):
pass
raise CustomError("Something went wrong")print("Value of x:", x)assertx = 10
assert x > 0import pdb
pdb.set_trace()Use the logging module instead of print.
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Program started")
logging.warning("This is a warning")
logging.error("An error occurred")✔ Better than print
✔ Used in production apps
In this lesson, you learned how to:
✔ Handle errors safely
✔ Prevent program crashes
✔ Raise and define custom exceptions
✔ Debug your code effectively
✔ Use logging like a professional developer
These skills are critical for building reliable applications in:
You are given a small Python program that reads student grades, calculates the average, and displays the result.
However, the script contains several common mistakes:
The goal is to find the bugs, fix them, and make the program more robust.
grades = []
n = input("How many grades do you want to enter? ")
for i in range(n):
grade = input("Enter grade: ")
grades.append(grade)
total = 0
for g in grades:
total = total + g
average = total / len(grades)
print("Average grade:", average)Find and fix the problems in the program so that it:
input() always returns a stringrange() needs an integertry/except to prevent crashes