Functions & Modules Lesson 21 of 23
Python Errors and Exceptions — try, except, finally
Read Python tracebacks, know the common error types, and handle problems with try, except, else and finally. Raise your own errors with raise.
Errors are normal. Every programmer sees them all day. The important skills are reading error messages so you can fix bugs quickly, and handling errors you can't prevent, like a user typing letters where a number belongs.
Reading a traceback
When something goes wrong, Python prints a traceback:
grades = [88, 92, 79]
print(grades[3])
Error
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(grades[3])
~~~~~~^^^
IndexError: list index out of rangeRead it from the bottom up: the last line names the error type and what happened. Above it, Python shows the file, the line number and the exact code.
Common error types
| Error | Usual cause |
|---|---|
SyntaxError | Typo in the code: missing colon, quote or bracket |
IndentationError | Wrong or missing indentation |
NameError | Misspelled or undefined variable |
TypeError | Wrong type, like "5" + 1 |
ValueError | Right type, wrong value, like int("abc") |
IndexError | List index doesn't exist |
KeyError | Dictionary key doesn't exist |
ZeroDivisionError | Dividing by zero |
FileNotFoundError | Opening a file that isn't there |
try and except
Put code that might fail inside try. If an error happens, Python jumps to except instead of crashing:
try:
age = int(input("Age: "))
print(f"Next year you'll be {age + 1}.")
except ValueError:
print("Please type a number, like 15.")
Output
Age: fifteen Please type a number, like 15.
Asking until the input is valid
while True:
try:
grade = float(input("Grade (0-100): "))
if 0 <= grade <= 100:
break
print("Must be from 0 to 100.")
except ValueError:
print("That's not a number.")
print("Saved:", grade)
Output
Grade (0-100): abc That's not a number. Grade (0-100): 120 Must be from 0 to 100. Grade (0-100): 89.5 Saved: 89.5
This pattern makes your programs "student-proof". Use it whenever you read numbers from input().
Handling different errors
try:
total = int(input("Total pesos: "))
people = int(input("Number of people: "))
print(f"Each pays ₱{total / people:.2f}")
except ValueError:
print("Numbers only, please.")
except ZeroDivisionError:
print("There must be at least one person.")
Output
Total pesos: 500 Number of people: 0 There must be at least one person.
else and finally
try:
f = open("grades.txt")
except FileNotFoundError:
print("No saved grades yet.")
else:
print("Loaded:", f.read().split()) # runs only if there was no error
f.close()
finally:
print("Done checking files.") # always runs
Output
No saved grades yet. Done checking files.
Getting the error message
try:
int("12abc")
except ValueError as e:
print("Problem:", e)
Output
Problem: invalid literal for int() with base 10: '12abc'
raise: creating your own errors
def set_grade(grade):
if not 0 <= grade <= 100:
raise ValueError(f"Invalid grade: {grade}")
return grade
try:
set_grade(150)
except ValueError as e:
print(e)
Output
Invalid grade: 150
Raising errors in your functions stops bad data early, close to where the problem started.
Debugging tips
- Read the last line of the traceback first, then go to the line number it shows.
- Check the line above too: a missing bracket or quote is often reported one line late.
- Add
print()statements to see what your variables contain. - Check types with
print(type(x))when you see aTypeError. - Copy the last line of the error into a search engine. Someone has had the same problem.
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04