Exceptions
try:
n = int("abc")
print("never printed")
except ValueError:
print("Not a number!")
finally:
print("Done")Python tries the risky code inside try.
1Level 1 · BasicsBasics
Things go wrong: a user types "abc" where you expected a number, a file is missing, someone divides by zero. When Python hits a problem it raises an exception, and if nobody handles it, the program stops with an error message. This lesson shows how to read those messages and handle errors gracefully.
Reading an error message
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(10 / n)
ZeroDivisionError: division by zero
Read it from the bottom: the last line names the error type and what happened, and the lines above show where (line 2). Error messages are your friends. They tell you exactly where to look.
Common exceptions
| Exception | Typical cause |
|---|---|
ValueError | int("abc"): right type, wrong value |
TypeError | "5" + 5: wrong type for the operation |
ZeroDivisionError | dividing by zero |
IndexError | list index out of range |
KeyError | missing dictionary key |
NameError | misspelled or undefined variable |
FileNotFoundError | opening a file that doesn't exist |
try and except
Put risky code in a try block, and say what to do if a particular error happens in except:
try:
age = int(input("Age: "))
except ValueError:
print("Please type a whole number.")
Catch specific exceptions. A bare except: also hides typos and real bugs.
else and finally
else:runs only if no exception happened.finally:runs always, which is useful for clean-up such as closing a file.
Getting the message and raising your own
except ValueError as e: stores the error in e, so you can print its message. You can also raise exceptions yourself when your function gets bad input:
if amount < 0:
raise ValueError("amount can't be negative")
Key points: read tracebacks from the bottom up; wrap risky code in try/except; catch specific exception types;elseruns on success andfinallyalways runs;raisesignals a problem yourself.
See it in actiontry/except catches the bad value
When int("abc") fails, Python jumps to the except block and then carries on with the loop.
Try it yourselfExample 1: Catching a ValueError
Change the input to a number and run again.
Output appears hereCatch bad input
Fill the blanks so typing abc prints Not a number instead of crashing.
text = input() : n = int(text) print(n * 2) ValueError: print("Not a number")
Example 2: Several kinds of error
Each except handles a different problem. Try changing the divisor or the index.
Output appears hereDividing by zero
This should print Can't divide by zero when b is 0, but it crashes because it catches the wrong error. Fix it.
Safe division
Read two whole numbers (one per line) and print a ÷ b with //. If b is 0 print Error: zero; if either isn't a number print Error: number.
Example input10
3Expected output3
Example 3: else and finally
else runs only on success; finally runs either way.
Output appears hereAlways say goodbye
Fill the blank so Done is printed whether or not an error happened.
try: print(int("7") + 1) except ValueError: print("Bad number") : print("Done")
Example 4: Raising your own exception
The function refuses bad input, and the caller decides what to do about it.
Output appears hereRaise your own error
Write set_age(age) that raises ValueError("Age can't be negative") for a negative age and otherwise returns it. Then try set_age(-3) and print the error message.
2Level 2 · IntermediateValidating input and raising errors
Retry until valid
Wrap int(input()) in a loop with try/except ValueError, so a typo asks again instead of crashing.
Raise the right built-in error
raise ValueError("need 100 Tk more") stops a function with a clear message. Pick the built-in type that fits (ValueError for a bad value, TypeError for the wrong kind of thing), so callers can catch exactly the problem they care about. After the Classes lesson you will be able to make your own error types.
Catch narrow, not wide
except Exception: also hides your own bugs (a typo in a variable name becomes a silent failure). Catch the specific errors you expect.
EAFP vs LBYL
Python style is often "easier to ask forgiveness than permission": try the action and handle the error, rather than checking every condition first.
See it in actionWhere the error jumps
Watch the arrow jump from the failing line straight into except, skipping the rest of try.
Example 5: Ask again until the input is valid
The Input box has two bad answers before a good one.
Output appears hereExample 6: Raising an error for a bank account
withdraw() raises ValueError with a clear message; the caller catches only that, so other bugs would still show.
Output appears here3Level 3 · AdvancedException chains, groups and clean-up
raise ... from ...
When you turn a low-level error into a clearer one, raise ValueError("bad port") from e keeps the original as the cause, so nothing is lost when debugging.
Exception hierarchy
Exceptions are classes in a tree: ZeroDivisionError is an ArithmeticError, which is an Exception. An except catches its class and all children, so order specific handlers before general ones.
ExceptionGroup and except*
Since Python 3.11, several errors can be raised together (common when validating a whole form or running tasks in parallel) and handled by type with except*.
Logging instead of print
logging.exception("...") inside an except records the message and the full traceback.
Example 7: Chaining with raise from
The clear message is what the user sees; __cause__ keeps the original error for whoever debugs it later.
Output appears hereExample 8: Collecting several errors at once
All problems in the form are reported together instead of one at a time.
Output appears heretry block small, just the line that can fail, and catch the most specific exception you can. except Exception catches almost everything, so use it only at the very top of a program, and print the error so bugs aren't hidden.What does this print?
try:
x = int("3.5")
print("A")
except ValueError:
print("B")
finally:
print("C")50 graded problems are waiting in Topic Practice.