When a line of code cannot do its job while the program runs (the file it opens is missing, the text it converts is not a number, the divisor is zero) Python raises an exception. Left alone, an exception stops the program and prints a traceback. With try and except you can catch it, respond sensibly and carry on. This lesson covers try, except, else, finally, raise and custom exceptions.
In this lesson you will learn
- How
try/exceptcatches errors - How to handle different errors differently
- What the
elseandfinallyblocks are for - How to raise your own errors
- How to define a custom exception class
try, except, else and finally
values = ["42", "abc", "0"]
for text in values:
try:
number = int(text)
result = 100 / number
except ValueError:
print(f"'{text}' is not a number")
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print(f"100 / {number} = {result}")
finally:
print("-- done with", text)
Output
100 / 42 = 2.380952380952381
-- done with 42
'abc' is not a number
-- done with abc
Cannot divide by zero
-- done with 0
- Code that might fail goes in
try. - Each
exceptnames the error type it handles.int("abc")raisesValueError; dividing by zero raisesZeroDivisionError. elseruns only when thetryblock raised nothing, which keeps the “success” code apart from the risky code.finallyruns every time, error or not. It is the place for clean-up such as closing connections.
Raising Errors and Custom Exceptions
class InsufficientFunds(Exception):
pass
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("amount must be positive")
if amount > balance:
raise InsufficientFunds(f"need {amount - balance} more")
return balance - amount
for amt in (300, -5, 900):
try:
print("New balance:", withdraw(500, amt))
except (ValueError, InsufficientFunds) as e:
print(type(e).__name__ + ":", e)
Output
New balance: 200
ValueError: amount must be positive
InsufficientFunds: need 400 more
raise ValueError("message")signals a problem from your own code. The caller decides how to handle it.- Custom exceptions are classes that inherit from
Exception. A clear name such asInsufficientFundsmakes the error self-explaining. except (A, B) as ecatches either type and stores the error object ine, whose text is the message you passed toraise.
Common Built-in Exceptions
| Exception | Typical cause |
|---|---|
ValueError | Right type, wrong value: int("abc") |
TypeError | Wrong type: "5" + 5 |
KeyError | Missing dictionary key |
IndexError | List index out of range |
ZeroDivisionError | Dividing by zero |
FileNotFoundError | Opening a file that does not exist |
AttributeError | Using a method the object does not have |
Common Mistakes
- A bare
except:. It catches everything, including typing mistakes in your own code and Ctrl+C. Name the exceptions you expect. - Putting too much code in
try. Wrap only the line that can fail, so other bugs are not hidden. - Silencing errors with
pass. At least log or print what happened. - Using exceptions for normal checks.
if key in d:is clearer than catchingKeyErrorfor simple cases.
Practice Exercises
Exercise 1. Write safe_int(text) that returns the integer, or None when the text is not a number.
Show answer
def safe_int(text):
try:
return int(text)
except ValueError:
return None
print(safe_int("12"), safe_int("x")) # 12 None
Exercise 2. Make set_age(n) raise ValueError when n is negative.
Show answer
def set_age(n):
if n < 0:
raise ValueError("age cannot be negative")
return n
Frequently Asked Questions
What is the difference between an error and an exception?
Syntax errors stop Python before the program runs. Exceptions happen while it runs and can be caught with try/except.
Does finally run if I return inside try?
Yes. finally runs before the function actually returns, which is why it is reliable for clean-up.
How do I see the full error while still handling it?
Use the traceback or logging module, for example logging.exception("failed") inside the except block.
Summary
tryholds risky code andexcepthandles named errors.elseruns on success andfinallyruns every time.raisesignals errors; subclassExceptionfor custom ones.- Catch specific exceptions, never everything.
Next: Python File Handling.
