Lesson 15 of 30
Exception Handling
try, except, finally, raising exceptions, and writing robust code.
What is an Exception?
An exception is a runtime error that interrupts normal program flow. Without handling, it prints a traceback and crashes. Common exceptions include ValueError, ZeroDivisionError, FileNotFoundError, and IndexError.
try / except
try:
num = int(input("Enter a number: "))
result = 100 / num
print(f"Result: {result}")
except ValueError:
print("That's not a valid integer.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else and finally
try:
f = open("data.txt")
except FileNotFoundError:
print("File not found!")
else:
print(f.read()) # runs only if no exception
finally:
print("Done.") # always runs
Raising Exceptions
def set_age(age):
if age < 0 or age > 120:
raise ValueError(f"Invalid age: {age}")
return age
try:
set_age(-5)
except ValueError as e:
print(f"Error: {e}")
✅ Best Practice
Always catch specific exception types rather than a bare except: clause, which can hide unexpected bugs.