Skip to main content
Practice

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:

  • try
  • except
  • else
  • finally

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 ValueError caused by int("abc").

3. else and finally

  • else runs only if no exception occurs.
  • finally runs 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.")
  • else confirms success.
  • finally is good for cleanup, such as closing files or connections.

Summary

KeywordPurpose
tryRun risky code
exceptHandle specific errors
elseRuns if no exception occurred
finallyAlways runs, used for cleanup

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.