How Python manages and recovers from runtime errors
Errors happen — missing files, invalid input, network issues, or unexpected data. Without handling them, your program may crash. Python’s try/except system lets you catch and respond to errors gracefully.
The basic pattern looks like this:
try:
# Code that might fail
risky_operation()
except:
# Code that runs if an error occurs
print("Something went wrong!")
It’s best practice to catch specific error types:
try:
number = int("abc")
except ValueError:
print("Invalid number!")
You can handle different errors differently:
try:
file = open("data.txt")
value = int(file.read())
except FileNotFoundError:
print("File not found.")
except ValueError:
print("File does not contain a valid number.")
The else block runs only if no exception occurs:
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Success:", result)
The finally block always runs, whether an error occurred or not:
try:
file = open("example.txt")
content = file.read()
except FileNotFoundError:
print("File missing.")
finally:
print("Done trying to read the file.")
You can trigger errors intentionally using raise:
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
return age
finally for cleanup (closing files, releasing resources).try blocks small and focused.Now that you understand error handling, you're ready to explore object‑oriented programming in Lesson 12: Object‑Oriented Programming Basics.
← Back to Lesson Index