From Full Stack to AI: File and Exception Handling in Python
Python File and Exception Handling for Full Stack and AI Developers

I’m a full-stack developer who enjoys building practical, scalable applications with React.js, Node.js, and Next.js. My journey into open source started with Hacktoberfest 2023, and it opened the door to real collaboration, learning from global contributors, and supporting early developers as they grow.
Since then, I’ve contributed to and mentored in programs like GSSoC’24, SSOC’24, and C4GT’24. As a Google Gen AI Exchange Hackathon ’24 Finalist and a Google Women Techmakers Ambassador, I’ve had the chance to help communities explore AI and build meaningful solutions. I’m also part of the Top 1% mentors on Topmate, where I guide students on open source, career building, and technical growth.
My work has been featured at Times Square NYC, and I’ve spoken on international podcasts about tech, learning, and community. I’ve also written technical content for CoderArmy and continue to share insights through articles and public posts. LinkedIn has recognized my work with seven Top Voice badges as well as Golden Badges in research, critical thinking, teamwork, and interpersonal skills.
I completed my MCA from Chandigarh University in 2023 and continue to stay curious by exploring AI, building new projects, and contributing to developer communities. Whether it’s improving a UI, debugging backend logic, or helping someone with their first pull request, I enjoy learning alongside others.
If you want to collaborate, learn together, or discuss an idea, feel free to reach out at kumaripayal7488@gmail.com
When you move from full stack development into AI or data work, Python becomes your daily tool. In real projects, things go wrong often. A missing file, a wrong input type, or an unexpected value can break your code. Exception and file handling help you write code that fails gracefully instead of crashing suddenly. This is a basic but very important habit to build early.
This article is written like a personal learning note. Simple examples, clear outputs, and chai based stories to make things relatable.
What is error handling in Python
Error handling is how we deal with runtime problems in our code. These are issues that Python only discovers while running the program.
For example, trying to access data that does not exist.
Example
orders = ["masala", "ginger"]
print(orders[2])
Output
IndexError: list index out of range
Explanation
The list has only two items. Index 2 does not exist. Python stops the program and shows an error. In real applications, we do not want our program to stop like this. We want to handle the situation properly.
That is where exception handling comes in.
Try and except
try lets you test code that might fail.except lets you handle the error instead of crashing.
Example
chai_menu = {"masala": 30, "ginger": 40}
try:
chai_menu["elaichi"]
except KeyError:
print("The key that you are trying to access does not exist")
print("Hello chai code")
Output
The key that you are trying to access does not exist
Hello chai code
Explanation
The key elaichi is not in the dictionary. Python raises a KeyError.
Instead of stopping the program, the except block runs.
The program continues and prints the next line.
Try, except, else, and finally
These four together give you full control.
try: code that may fail
except: runs if an error happens
else: runs if no error happens
finally: always runs
Example
def serve_chai(flavor):
try:
print(f"Preparing {flavor} chai...")
if flavor == "unknow":
raise ValueError("We don't know that flavor")
except ValueError as e:
print("Error:", e)
else:
print(f"{flavor} chai is served")
finally:
print("Next customer please")
serve_chai("masala")
serve_chai("unknown")
Output
Preparing masala chai...
masala chai is served
Next customer please
Preparing unknown chai...
Error: We don't know that flavor
Next customer please
Explanation
For masala, no error occurs so else runs.
For unknown, a ValueError is raised and caught.finally runs every time, like cleaning up after serving a customer.
Catching multiple exceptions
Sometimes different things can go wrong and each needs a different response.
Example
def process_order(item, quantity):
try:
price = {"masala": 20}[item]
cost = price * quantity
print(f"total cost is {cost}")
except KeyError:
print("Sorry that chai is not on menu")
except TypeError:
print("Quantity must be in number")
process_order("ginger", 2)
process_order("masala", "two")
Output
Sorry that chai is not on menu
total cost is twotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwo
Explanation
The first call fails because ginger is not in the menu.
The second call does not raise a TypeError. Python allows string multiplication, so "two" * 20 repeats the string. This shows why understanding data types is important and why logic checks matter.
Raising your own errors
Sometimes Python will not raise an error automatically, but logically something is wrong. You can raise your own exceptions.
Example
def brew_chai(flavor):
if flavor not in ["masala", "ginger", "elaichi"]:
raise ValueError("Unsupported chai flavor")
print(f"Brewing {flavor} chai...")
brew_chai("mint")
Output
ValueError: Unsupported chai flavor
Explanation
Mint is not allowed. We manually tell Python that this is an error. This makes our code more strict and predictable.
Custom exceptions
For bigger projects, custom exceptions make errors clearer and easier to debug.
Example
class OutOfIngredientsError(Exception):
pass
def make_chai(milk, sugar):
if milk == 0 or sugar == 0:
raise OutOfIngredientsError("Missing milk or sugar")
print("chai is ready...")
make_chai(0, 1)
Output
OutOfIngredientsError: Missing milk or sugar
Explanation
Instead of using a generic error, we created our own. This helps when many different error cases exist in a system.
Mini project: chai billing with exception handling
This combines everything learned so far.
Example
class InvalidChaiError(Exception):
pass
def bill(flavor, cups):
menu = {"masala": 20, "ginger": 40}
try:
if flavor not in menu:
raise InvalidChaiError("that chai is not available")
if not isinstance(cups, int):
raise TypeError("Number of cups must be an integer")
total = menu[flavor] * cups
print(f"Your bill for {cups} cups of {flavor} chai: rupees {total}")
except Exception as e:
print("Error:", e)
finally:
print("Thank you for visiting")
bill("mint", 2)
bill("masala", "four")
bill("ginger", 3)
Output
Error: that chai is not available
Thank you for visiting
Error: Number of cups must be an integer
Thank you for visiting
Your bill for 3 cups of ginger chai: rupees 120
Thank you for visiting
Explanation
Each bad input is handled cleanly. The program never crashes. This is how real systems should behave.
File handling with try, except, and with
Files also need proper handling to avoid leaks and corruption.
Old way
file = open("order.txt", "w")
try:
file.write("Masala chai - 2 cups")
finally:
file.close()
Better way using with
with open("order.txt", "w") as file:
file.write("ginger tea - 4 cups")
Output in order.txt
ginger tea - 4 cups
Explanation
with automatically closes the file even if an error happens. This is cleaner and safer.
Closing thoughts
Exception and file handling are not advanced topics. They are foundations. When you move into AI, data pipelines, or backend systems, small mistakes can cause big failures. Learning to handle errors step by step builds confidence and discipline.
Write code that expects things to go wrong. That mindset matters more than any library.





