Exception Handling
Learn to handle errors gracefully using try-except blocks and best practices for debugging.
What are Exceptions?
Exceptions are errors that occur during execution. If not handled, they crash your program.
Try-Except Blocks
Use try to wrap code that might fail and except to handle specific errors.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Finally and Else
finally always runs (great for cleanup like closing files), and else runs only if no exception occurred.
try:
f = open("data.txt", "r")
except FileNotFoundError:
print("File missing")
else:
content = f.read()
finally:
# This runs regardless of success or failure
print("Cleanup complete")
f = open("data.txt", "r")
except FileNotFoundError:
print("File missing")
else:
content = f.read()
finally:
# This runs regardless of success or failure
print("Cleanup complete")
Raising Exceptions
You can intentionally trigger an exception using raise.
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
if age < 0:
raise ValueError("Age cannot be negative")
return age
โ Practice (15 minutes)
- Write a program that asks for user input and tries to convert it to an integer.
- Use
try-exceptto handle cases where the user enters non-numeric text. - Create a function that raises a
PermissionErrorif a user isn't an "admin".