When you write Python programs, things can go wrong — a file might not exist, a user may enter the wrong input, or a network request might fail. Instead of letting the program crash, Python lets you handle these problems gracefully using exceptions.
📝 If You Want to Practice the Code
If you plan to practice the Python code mentioned within this blog post, you’ll need a working Python environment. You can execute the commands in one of the following ways (choose only one option):
- From a Python prompt in your terminal or command line – see Getting Started with Python and Virtual Environment in Python and How to Set One Up
- Using Miniconda and Jupyter Notebook – see How to Install and Set Up Miniconda and Install Jupytor Notebook Windows, How to Install and Set Up Miniconda on MacOS, How to Install and Set Up Miniconda on Linux (Ubuntu), and Getting Started with Jupyter Notebooks.
- On Google Colab (browser-based, no installation required) – see Getting Started with Google Colab.
- Through VS Code – see Setting Up VS Code for Python Development.
👉 Choose whichever environment you’re most comfortable with. If you haven’t set up Python yet, start with one of the installation posts before trying the examples here.
🔹 What Are Exceptions?
An exception is an error that happens while the program is running.
Example:
print(10 / 0) # Division by zero
👉 This will crash with:
ZeroDivisionError: division by zero
To avoid this, we use try/except blocks.
🔹 Using try and except
The basic structure is:
try:
# risky code
print(10 / 0)
except ZeroDivisionError:
print("You can’t divide by zero!")
👉 Output:
You can’t divide by zero!
🔹 Handling Multiple Exceptions
You can handle different errors separately:
try:
number = int("abc") # invalid conversion
except ValueError:
print("That’s not a valid number!")
except ZeroDivisionError:
print("You can’t divide by zero!")
🔹 The else Block
If no exception occurs, the else block runs:
try:
x = 5 / 1
except ZeroDivisionError:
print("Division error")
else:
print("No error, result is:", x)
👉 Output:
No error, result is: 5.0
🔹 The finally Block
finally always runs — useful for cleanup (like closing a file or database connection).
try:
f = open("data.txt")
content = f.read()
except FileNotFoundError:
print("File not found!")
finally:
print("This runs no matter what.")
🔹 Raising Your Own Exceptions
You can create your own errors with raise:
age = -5
if age < 0:
raise ValueError("Age cannot be negative!")
📝 Mini Task
Write a program that:
- Asks the user to input a number.
- Handles cases where the input is not a number.
- Handles division by zero.
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result is:", result)
except ValueError:
print("Please enter a valid number.")
except ZeroDivisionError:
print("You cannot divide by zero.")
finally:
print("Program finished.")
✅ Summary
- try/except is used to catch and handle errors.
- else runs only when there is no error.
- finally always runs, even if there’s an error.
- You can raise exceptions manually when input or logic is invalid.
With error handling, your programs won’