Exception Handling with try/except
Programs sometimes crash due to unexpected errors — such as dividing by zero or trying to open a file that doesn’t exist.
Instead of letting your program stop abruptly, you can use exception handling to manage errors gracefully.
Python provides four key tools for handling exceptions:
tryexceptelsefinally
1. try and except
Wrap potentially risky code in a try block. If an error occurs, Python jumps to the corresponding except block.
try:
result = 10 / 0
except ZeroDivisionError:
print("Oops! You can't divide by zero.")
- The division causes an error.
- Python skips the crash and shows a message instead.
2. Handling Multiple Error Types
You can handle multiple error types by using separate except blocks for each one.
Handling Multiple Error Types
try:
num = int("abc")
except ValueError:
print("That's not a valid number.")
except TypeError:
print("Type mismatch.")
- This handles a
ValueErrorcaused byint("abc").
3. else and finally
elseruns only if no exception occurs.finallyruns regardless of whether an exception occurs.
else and finally
try:
value = int("42")
except ValueError:
print("Conversion failed.")
else:
print("Conversion succeeded:", value)
finally:
print("Done checking.")
elseconfirms success.finallyis good for cleanup, such as closing files or connections.
Summary
| Keyword | Purpose |
|---|---|
try | Run risky code |
except | Handle specific errors |
else | Runs if no exception occurred |
finally | Always runs, used for cleanup |
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.