👋 Work With Me

I help startups and teams build production-ready apps with Django, Flask, and FastAPI.

Let’s Talk →

I'm always excited to take on new projects and collaborate with innovative minds.

Address

No 7 Street E, Federal Low-cost Housing Estate, Kuje, Abuja 903101, Federal Capital Territory

Social Links

Tutorials

Python Tutorial – Lesson 14: Error Handling & Exceptions in Python

Errors are a part of programming — everyone makes mistakes! But Python gives us a way to handle errors gracefully so that our programs don’t just crash when something goes wrong.

Python Tutorial – Lesson 14: Error Handling & Exceptions in Python

Errors are a part of programming — everyone makes mistakes! But Python gives us a way to handle errors gracefully so that our programs don’t just crash when something goes wrong. This is done using Exceptions and the try-except block.


✅ What are Exceptions?

An Exception is an error that occurs while a program is running.
For example:

 
print(10 / 0)   # Division by zero 

👉 This will give an error: ZeroDivisionError.

If not handled, the program will stop. That’s where exception handling comes in.


🔹 Using try-except

We can use try-except to handle errors without stopping the program:

 
try:
   number = int(input("Enter a number: "))
   print(10 / number)
except ZeroDivisionError:
   print("Oops! You can’t divide by zero.")
except ValueError:
   print("Invalid input. Please enter a number.")

Output Example:

 
Enter a number: 0
Oops! You can’t divide by zero.

🔹 The else Block

You can add an else block that runs if no exception occurs:

 
try:
   num = int(input("Enter a positive number: "))
except ValueError:
   print("Invalid input.")
else:
   print(f"Great! You entered {num}.")

🔹 The finally Block

The finally block always runs, whether an exception happened or not.
This is useful for cleaning up resources (like closing files or database connections):

 
try:
   file = open("example.txt", "r")
   print(file.read())
except FileNotFoundError:
   print("File not found.")
finally:
   print("Closing file (if opened).")

🔹 Raising Exceptions Manually

You can raise your own exceptions when something isn’t right:

 
age = int(input("Enter your age: "))

if age < 0:
   raise ValueError("Age cannot be negative!")
else:
   print("Valid age entered.")

📝 Quick Recap

  • try-except → Handle errors without crashing the program.
  • else → Runs only if no errors happen.
  • finally → Always runs (cleanup).
  • raise → Create custom exceptions.

🎯 Practice Exercises

  1. Write a program that asks for two numbers and divides them, but handles:
    • ZeroDivisionError
    • ValueError
  2. Open a file (like data.txt):
    • If it exists → print contents
    • If it doesn’t → show a friendly message
    • Use finally to close the file
  3. Create a function check_age(age) that:
    • Raises an exception if age < 18
    • Otherwise, prints “You are eligible!”

 

Next up: Lesson 15: Object-Oriented Programming (OOP) in Python

💼 Need a Developer?

I'm Kingsley Odume, a Django, Flask, and FastAPI developer with experience building SaaS platforms, APIs, and modern web apps. If you're a recruiter or business owner looking for a reliable software developer, let's connect!

🚀 Hire Me

Python, Python tutorials, Python Beginners series, Python Step-byStep
3 min read
Aug 20, 2025
By Kingsley Odume
Share

Leave a comment

Your email address will not be published. Required fields are marked *

Related posts

Aug 29, 2025 • 3 min read
Step-by-Step: Building a SaaS App with Django + Stripe Payments

Learn how to build a real-world SaaS app with Django and Stripe paymen...

Aug 21, 2025 • 3 min read
Final Wrap-Up: Python Tutorial Series for Beginners

Congratulations on completing the Python Tutorial Series! 🚀 In this w...

Aug 20, 2025 • 4 min read
Final Lesson: Mini Project – Putting It All Together in Python

In this final lesson, we’ll bring all those concepts together in a Min...

Your experience on this site will be improved by allowing cookies. Cookie Policy