Exception Handling in Python
When something goes wrong in Python — like dividing by zero or reading a missing file — the program raises an exception and normally crashes. Exception handling lets you catch the error and respond instead of crashing:
try:
number = int(input("Enter a number: "))
print(f"You entered {number}")
except ValueError:
print("That wasn't a valid number!")
If the user types "abc", the int() call fails, but instead of crashing, the except block runs a friendly message. Let's break this down.
The try/except block
You put risky code inside try. If an exception happens, Python jumps to the matching except block:
try:
result = 10 / 0 # this raises ZeroDivisionError
print(result) # this line is skipped
except ZeroDivisionError:
print("You can't divide by zero!")
The moment an error occurs in the try block, the rest of it is skipped and control moves to except.
Catching specific exceptions
It's good practice to catch the specific error you expect, not every possible error. Common ones include:
ValueError— wrong type of value (e.g.int("abc")).ZeroDivisionError— dividing by zero.FileNotFoundError— opening a file that doesn't exist.KeyError— accessing a missing dictionary key.IndexError— accessing a list position that doesn't exist.
try:
with open("data.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("Sorry, that file doesn't exist.")
Handling multiple exceptions
You can have several except blocks, or catch multiple types in one:
try:
value = int(input("Number: "))
answer = 100 / value
print(answer)
except ValueError:
print("Please enter a whole number.")
except ZeroDivisionError:
print("Zero won't work — try another number.")
else and finally
- The
elseblock runs only if no exception occurred. - The
finallyblock runs no matter what — perfect for cleanup.
try:
number = int(input("Enter a number: "))
except ValueError:
print("Not a number.")
else:
# Runs only if the try block succeeded
print(f"Great, you entered {number}")
finally:
# Always runs, error or not
print("Thanks for using the program.")
Want to learn this properly?
Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.
Browse coursesRaising your own exceptions
You can trigger an exception deliberately with raise — useful for enforcing rules:
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
try:
set_age(-5)
except ValueError as error:
print(f"Error: {error}") # Error: Age cannot be negative
The as error part captures the exception object so you can read its message.
A practical example
# Safely divide two numbers entered by the user
try:
a = float(input("First number: "))
b = float(input("Second number: "))
result = a / b
except ValueError:
print("Please enter valid numbers.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print(f"Result: {result}")
finally:
print("Calculation finished.")
Common mistakes
- Catching everything with a bare
except:: This hides real bugs and makes debugging painful. Catch specific exceptions you actually expect. - Putting too much in the
tryblock: Wrap only the line(s) that can fail. A hugetrymakes it unclear what you're guarding against. - Silently passing errors:
except: passswallows problems without a trace. At least log or print what went wrong. - Using exceptions for normal flow: Don't rely on try/except for ordinary conditions you can check with an
if. Use it for genuinely exceptional situations. - Confusing
elseandfinally:elseruns only on success;finallyruns always. Usefinallyfor cleanup like closing resources.
FAQ
What's the difference between an error and an exception? In everyday speech they're similar. In Python, exceptions are the objects raised when something goes wrong; you handle them with try/except.
Should I always use try/except? No. Use it where an error is genuinely possible and you have a sensible way to respond. Over-wrapping every line makes code hard to read.
Can I create my own exception types?
Yes — define a class that inherits from Exception. That's useful in larger programs to signal specific problems clearly.
Exception handling is essential for File Handling in Python and any program that takes user input. It also pairs with Functions in Python for validating arguments. More topics on the Python learning hub.
Want to learn this properly? Join the waitlist for our Python course — taught in Jalgaon, beginner-friendly.
Want to learn this properly?
Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.
Browse coursesInstructor, Infoplanet
Kedar Kabra teaches Python at Infoplanet, helping beginners become confident programmers through hands-on, project-first practice.
Related guides
Dictionaries in Python
Understand Python dictionaries — storing data as key-value pairs — including adding, accessing, updating, looping, and safely reading values with .get().
File Handling in Python
Read from and write to files in Python using with open() — covering file modes, reading line by line, appending, and safe file handling.
Functions in Python
Define and use functions in Python — parameters, return values, default and keyword arguments — to write reusable, readable code.
