Python ยท Chapter 27 of 45
Python Exceptions
Errors that happen at runtime are called EXCEPTIONS. Handle them with `try` / `except` so your program doesn't crash.
Add `else` (runs when no error) and `finally` (always runs) blocks as needed.
Syntax
try:
risky()
except SomeError as e:
handle(e)
finally:
cleanup()Catching specific errors
Catch the narrowest exception you can handle. Avoid bare `except:` โ it hides bugs.
Raising your own
Use `raise ValueError('message')` to signal an error yourself.
Example 1 (python)
try:
x = int("abc")
except ValueError as e:
print("Bad number:", e)Output
Bad number: invalid literal for int() with base 10: 'abc'Catch a ValueError from a failed int() conversion.
Example 2 (python)
try:
result = 10 / 0
except ZeroDivisionError:
result = None
print(result)Output
NoneHandle division by zero gracefully.
Key points
- Wrap risky code in `try:`.
- Catch specific exceptions.
- `finally:` always runs (great for cleanup).
- Use `raise` to signal your own errors.
๐ก Note: Never use `except: pass` โ silently swallowing errors is one of the top causes of hard-to-find bugs.
