Lesson 5: Error Handling
Programs crash when unexpected things happen — a file that doesn't exist, a user enters text when you expect a number, a network request fails. Error handling lets your program recover gracefully instead of crashing.
Key Concepts
try / except
try:
result = int(input('Enter a number: '))
except ValueError:
print('That was not a number!')
Code in try runs normally. If an exception occurs, the except block handles it.
Specific Exceptions
Catch specific errors: except ValueError, except FileNotFoundError, except ZeroDivisionError. Use except Exception as e: to catch anything and inspect e. Avoid bare except: — it hides bugs.
else and finally
else: runs if no exception occurred. finally: always runs — great for cleanup (closing files, connections):
try: ...except: ...else: print('Success!')finally: print('Done')
Raising Exceptions
raise ValueError('Score must be 0-100')
You can raise exceptions intentionally to enforce rules in your own code. Good libraries validate inputs and raise clear error messages.
✅ Check Your Understanding
1. What does the try block do?
2. What exception does int('abc') raise?
3. When does the finally block run?