Drop #13 - Handling Errors Gracefully
In the last Python Drop, we explored the differences between lists, tuples, and sets.
Now it's time to face something every developer encounters: errors.
Good error handling is not about avoiding crashes at all costs, it's about writing code that fails predictably and gracefully.
Why Error Handling Matters
Python's philosophy is: "Errors should never pass silently, unless explicitly silenced."
This is why exception handling is central to Python's design. It allows you to separate normal logic from error recovery, making your programs more robust.
The Basics: try/except
try:
number = int("abc")
except ValueError:
print("Invalid number!")
Handling Multiple Exceptions
try:
data = {"name": "Alice"}
print(data["age"])
except KeyError:
print("Missing key!")
except TypeError:
print("Type mismatch!")
finally and else
try:
f = open("file.txt", "r")
content = f.read()
except FileNotFoundError:
print("File not found!")
else:
print("File read successfully.")
finally:
print("Always runs — closing resources.")
f.close()
Raising Exceptions
def divide(a: float, b: float) -> float:
if b == 0:
raise ZeroDivisionError("Cannot divide by zero.")
return a / b
Best Practices
class InsufficientBalanceError(Exception):
pass
Challenge for You
Imagine you're building a payment system.
How would you design a custom exception to represent "insufficient balance" and use it in your logic?
🔗 This post is part of the Python Drops series.
Up next: Drop #14 - Python List Comprehensions Demystified
Fullstack Software Engineer | Java | Spring Boot | React | AWS | Docker | PostgreSQL
2dGreat post! Well-structured error handling is what separates robust code from fragile code. Addressing exceptions clearly and predictably is fundamental for software maintainability and reliability.
Software Engineer | Node | Typescript | React | AWS
3dThoughtful post, thanks Arthur
Senior Software Engineer | PHP | Laravel | Node.js | NestJS | Go | Golang | Microservices | Docker | Kubernetes | GCP
3dThanks for sharing, Arthur
Senior .NET Software Engineer | Fullstack | C# | .NET | React | AWS | Azure
4dThanks for sharing, Arthur
Senior Software Engineer | C# .NET | Fullstack
4dThoughtful post, thanks Arthur