Error Handling
Errors happen. Programs trip sometimes.
Error handling is a soft landing.
Like putting a mat under a climbing wall.
You try a risky step. If it fails, you catch it and keep going.
try and except
Put risky code in try.
Put the backup plan in except.
If try works, except is skipped.
Catch a specific error
Name the error type you expect.
That way other bugs still show up loudly.
ZeroDivisionError for divide by zero
ValueError for bad conversions
TypeError for wrong kinds of values
KeyError for a missing dict key
else and finally
else runs when try had no error.
finally runs no matter what.
finally is good for cleanup steps.
Many except blocks
You can handle different errors in different ways.
raise your own error
Use raise when something is wrong on purpose.
Like blowing a whistle when a rule is broken.
Keep errors helpful
Tell the user what went wrong in plain words.
Do not hide every error forever.
Catch what you can fix. Let surprising bugs show.
Tip: Catch specific errors first. Use clear messages so future you knows what failed.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.