Skip to main content
Practice

Exception Handling with try/except

Sometimes, programs crash because of unexpected errors — like dividing by zero or accessing a file that doesn’t exist.
Instead of crashing, we can use exception handling to deal with those errors gracefully.

Python provides four key tools:

  • try
  • except
  • else
  • finally

1. try and except

Wrap risky code in a try block. If an error happens, Python jumps to the except block.

try:
result = 10 / 0
except ZeroDivisionError:
print("Oops! You can't divide by zero.")

Explanation:

  • The division causes an error.
  • Python skips the crash and shows a message instead.

2. Handling Multiple Error Types

You can catch different types of exceptions in separate except blocks.

try:
num = int("abc")
except ValueError:
print("That’s not a valid number.")
except TypeError:
print("Type mismatch.")

Explanation:

  • This handles a ValueError caused by int("abc").

3. else and finally

  • else runs only if no error occurs.
  • finally runs no matter what, even if there’s an error.
try:
value = int("42")
except ValueError:
print("Conversion failed.")
else:
print("Conversion succeeded:", value)
finally:
print("Done checking.")

Explanation:

  • else confirms success.
  • finally is good for cleanup (like closing files or connections).

Summary

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

What’s Next?

In the next lesson, we’ll learn how to read and write files to store and retrieve data.