What You Will Learn
Errors happen — files do not exist, users type the wrong thing, network requests fail. In this lesson, you will learn how to handle errors gracefully instead of letting your program crash.
What Happens Without Error Handling
age = int(input("Enter your age: "))
print(f"You are {age} years old.")
If the user types “hello” instead of a number:
Enter your age: hello
ValueError: invalid literal for int() with base 10: 'hello'
The program crashes. Not great.
try / except
Wrap the risky code in a try block, and handle the error in except:
try:
age = int(input("Enter your age: "))
print(f"You are {age} years old.")
except ValueError:
print("Please enter a valid number.")
Example interaction (bad input):
Enter your age: hello
Please enter a valid number.
The program continues instead of crashing.
Catching Specific Errors
Always catch the specific error type you expect:
# File might not exist
try:
with open("data.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("File not found. Starting fresh.")
content = ""
# Division by zero
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
The else Clause
else runs only if no error occurred:
try:
number = int(input("Enter a number: "))
except ValueError:
print("That was not a number.")
else:
print(f"Your number doubled: {number * 2}")
The finally Clause
finally always runs, whether or not an error occurred. Use it for cleanup:
try:
f = open("data.txt", "r")
content = f.read()
except FileNotFoundError:
print("File not found.")
finally:
print("Done attempting to read file.")
Asking Again Until Valid Input
Combine while True with try/except to keep asking until the user gives valid input:
while True:
try:
age = int(input("Enter your age: "))
if age < 0 or age > 150:
print("Age must be between 0 and 150.")
continue
break
except ValueError:
print("Please enter a whole number.")
print(f"Your age is {age}.")
Example interaction:
Enter your age: hello
Please enter a whole number.
Enter your age: -5
Age must be between 0 and 150.
Enter your age: 25
Your age is 25.
Common Exception Types
| Exception | When it occurs |
|---|---|
ValueError | Wrong type of value (e.g. int("hello")) |
TypeError | Wrong type for an operation |
FileNotFoundError | File does not exist |
ZeroDivisionError | Dividing by zero |
IndexError | List index out of range |
KeyError | Dictionary key does not exist |
What You Learned
try/exceptcatches errors and prevents crashes- Always catch the specific exception type
elseruns when no error occurredfinallyalways runs — useful for cleanup- Combine with
while Trueto retry on bad input
In the final lesson, you will put everything together and build a complete command-line application.