No matter how careful you are, things go wrong while a program runs. A user types "abc" when you asked for a number, a file you want to open does not exist, or you accidentally divide by zero. When this happens, Python stops your program and prints an error.
Exception handling lets you catch these errors and decide what to do instead of letting the program crash. It is what separates a fragile script from a reliable program.
What is an Exception?
An exception is an error that happens while the program is running. If it is not handled, Python stops the program and shows a traceback.
print("Start")
print(10 / 0)
print("End")Output:
Start
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(10 / 0)
~~~^~~
ZeroDivisionError: division by zeroNotice that "End" never prints. The program stopped at line 2. Read a traceback from the bottom up: the last line tells you the exception type (ZeroDivisionError) and the message (division by zero), and the lines above show where it happened.
Errors vs exceptions
A syntax error (like a missing colon) is found before the program even starts, so it cannot be caught. An exception happens while the code runs, and that is what we can handle.
Common Built-in Exceptions
| Exception | When it happens | Example |
|---|---|---|
ZeroDivisionError | Dividing by zero | 10 / 0 |
ValueError | Right type, wrong value | int("abc") |
TypeError | Wrong type for an operation | "5" + 5 |
IndexError | List index out of range | [1, 2][5] |
KeyError | Missing dictionary key | {"a": 1}["b"] |
NameError | Using an undefined variable | print(xyz) |
AttributeError | Object has no such attribute | "hi".push() |
FileNotFoundError | Opening a file that does not exist | open("missing.txt") |
ModuleNotFoundError | Importing a module that is not installed | import notreal |
The try and except Block
Put the risky code inside try. If an exception happens, Python jumps to the matching except block instead of crashing.
try:
print(10 / 0)
except ZeroDivisionError:
print("You can't divide by zero!")
print("Program continues")Output:
You can't divide by zero!
Program continuesHow it works step by step:
Python runs the code inside
tryline by line.If no exception occurs, the
exceptblock is skipped completely.If an exception occurs, the rest of the
tryblock is skipped and Python looks for anexceptthat matches the exception type.If a match is found, that block runs and the program continues after the whole
trystatement. If no match is found, the program crashes as usual.
Handling Multiple Exceptions
Separate except blocks
Different errors often need different messages:
def convert(value):
try:
number = int(value)
print("Converted:", number)
except ValueError:
print(f"'{value}' is not a valid number")
except TypeError:
print(f"Cannot convert {type(value).__name__} to int")
convert("42")
convert("abc")
convert(None)Output:
Converted: 42
'abc' is not a valid number
Cannot convert NoneType to intPython checks the except blocks from top to bottom and runs only the first one that matches.
One block for several exceptions
If you want the same handling for several types, group them in a tuple:
for v in ["5", "x", [1]]:
try:
n = int(v)
print("Got", n)
except (ValueError, TypeError) as e:
print("Error:", e)Output:
Got 5
Error: invalid literal for int() with base 10: 'x'
Error: int() argument must be a string, a bytes-like object or a real number, not 'list'Getting the error message with as
except SomeError as e stores the exception object in e. Printing it gives the message:
try:
nums = [1, 2, 3]
print(nums[5])
except IndexError as e:
print("Error:", e)
print("Type:", type(e).__name__)Output:
Error: list index out of range
Type: IndexErrorelse and finally
A try statement can have two more optional parts:
elseruns only if no exception happened intry.finallyruns always, whether there was an exception or not. It is used for clean-up work like closing files or connections.
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result:", result)
finally:
print("Done")
divide(10, 2)
divide(5, 0)Output:
Result: 5.0
Done
Cannot divide by zero
DoneThe flow looks like this:
try
/ \
no error error
| |
else except
\ /
finally
|
rest of programWhy use else instead of putting the code in try? It keeps the try block small, so you only catch errors from the line you actually expect to fail.
finally runs even when the try block uses return:
def test():
try:
return "from try"
finally:
print("finally runs before returning")
print(test())Output:
finally runs before returning
from tryRaising Exceptions with raise
You can trigger an exception yourself when your function receives invalid data. This is better than silently continuing with wrong values.
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
print("Age set to", age)
try:
set_age(21)
set_age(-5)
except ValueError as e:
print("Error:", e)Output:
Age set to 21
Error: Age cannot be negativeRe-raising an exception
Sometimes you want to do something (like logging) and then let the error continue upward. A bare raise inside an except block re-raises the same exception:
def load():
try:
return int("abc")
except ValueError:
print("Logging the problem...")
raise
try:
load()
except ValueError as e:
print("Caught again:", e)Output:
Logging the problem...
Caught again: invalid literal for int() with base 10: 'abc'Custom Exceptions
For your own programs, you can create exception types with meaningful names. A custom exception is a class that inherits from Exception. You will learn classes and inheritance properly in later chapters; for now, just copy this pattern:
class InsufficientBalanceError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientBalanceError(f"Need {amount}, but only {balance} available")
return balance - amount
try:
print(withdraw(1000, 300))
print(withdraw(1000, 5000))
except InsufficientBalanceError as e:
print("Transaction failed:", e)Output:
700
Transaction failed: Need 5000, but only 1000 availableA name like InsufficientBalanceError tells the reader exactly what went wrong, which a generic ValueError cannot.
The Exception Hierarchy
Exceptions are organised in a family tree. Catching a parent also catches all of its children.
BaseException
├── KeyboardInterrupt (Ctrl + C)
├── SystemExit (sys.exit())
└── Exception (almost everything else)
├── ArithmeticError
│ └── ZeroDivisionError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── OSError
│ └── FileNotFoundError
├── TypeError
└── ValueErrorSo except LookupError catches both IndexError and KeyError. This is also why the order of except blocks matters: put specific exceptions first and general ones last, or the specific block will never run.
A Practical Example: Safe Number Input
A classic use of exception handling is asking the user again until they enter valid data:
while True:
text = input("Enter your age: ")
try:
age = int(text)
if age < 0:
raise ValueError("age cannot be negative")
except ValueError as e:
print("Invalid input:", e)
else:
print("Your age is", age)
breakSample run:
Enter your age: abc
Invalid input: invalid literal for int() with base 10: 'abc'
Enter your age: -3
Invalid input: age cannot be negative
Enter your age: 25
Your age is 25Common Mistakes
Using a bare
except:. It catches everything, includingKeyboardInterrupt(so Ctrl + C stops working) and your own typos likeNameError. Always name the exception you expect.Catching
Exceptionand ignoring it. Writingexcept Exception: passhides bugs. If you catch broadly, at least print or log the error.Putting too much code inside
try. Keep only the line that can fail inside it; move the rest toelse.Wrong order of
exceptblocks.except Exceptionbeforeexcept ValueErrormeans theValueErrorblock can never run.Using exceptions where a simple check is clearer. For a dictionary,
marks.get("Ravi", "Not found")is often simpler than catchingKeyError.
Summary
| Keyword | Purpose |
|---|---|
try | Wraps code that might fail |
except | Handles a specific exception |
else | Runs if no exception occurred |
finally | Always runs (clean-up) |
raise | Triggers an exception yourself |
Catch only the exceptions you expect, handle them meaningfully, and let unexpected errors surface so you can fix them.
Interview tip: A common question is "What is the difference between else and finally?" Answer: else runs only when the try block succeeds; finally runs every time, even if there is an exception or a return.
In the next chapter, you will use exception handling right away while working with files, where errors like FileNotFoundError are very common.