What is an Exception?
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Errors occur even in well-written software. In Python, runtime errors are represented as exception objects that halt execution unless caught and handled gracefully.
Syntax errors versus runtime exceptions
Exception is an error that happens while a program is running. Python stops the normal flow and reports the error unless the code handles it.
A SyntaxError occurs when code violates Python grammar rules, stopping execution before running. An Exception occurs while code is actively executing.
# Runtime error during executionresult = 100 / 0Example 1 · Check text before converting it
quantity_text = "12x"
if quantity_text.isdigit(): print(int(quantity_text))else: print(f"{quantity_text!r} is not a whole number")'12x' is not a whole number
What this code does
isdigit()is True only when every character is a digit."12x"has a letter, so the check fails andint()is never called.- No
ValueErroris raised because the bad text never reachesint().
Python raises ZeroDivisionError: division by zero and prints a traceback detailing the exact line.
Reading a Python traceback
Traceback is the report Python prints for an unhandled exception. It lists the calls that led to the error. The last line names the error type and message.
When an unhandled exception occurs, Python prints a traceback showing the call stack from oldest to newest call.
def parse_age(s): return int(s)
# parse_age("twenty") -> ValueError: invalid literal for int() with base 10: 'twenty'Read the traceback from bottom to top: the bottom line displays the exception type and explanation, while lines above show the call chain.
Common built-in exceptions
Built-in exception is an error type that Python already provides, such as ValueError or KeyError. The name tells you what kind of problem happened.
Every Python programmer meets these five exceptions early:
Example 2 · Check the index before reading
data = ["10", "20", "30"]index = 2
if 0 <= index < len(data): print(f"Value: {data[index]}")else: print("Index out of range")Value: 30
What this code does
- Verifies that index 2 is within valid list bounds (0 to 2).
- Safely outputs 'Value: 30' without triggering an IndexError.
Example 3 · Read a price with a default
prices = {"pen": 10, "book": 50}order = "bag"
price = prices.get(order, 0)print(f"Price of {order}: {price}")Price of bag: 0
What this code does
prices["bag"]would raise aKeyError.getreturns the second value, 0, when the key is missing.- The program keeps running and prints a safe answer.
ValueError: invalid value for valid type (e.g. int("abc")). TypeError: operation on incompatible types (e.g. '5' + 5). ZeroDivisionError: division or modulo by zero.
IndexError: accessing out-of-bounds list index (e.g. [1, 2][5]). KeyError: looking up a dictionary key that is not there (e.g. {'a': 1}['b']).
Next step
Check your understanding
8 quick questions