Drop #13 - Handling Errors Gracefully

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!")        

  • The try block contains code that may raise an exception.
  • The except block handles the error in a controlled way.


Handling Multiple Exceptions

try:

    data = {"name": "Alice"}

    print(data["age"])

except KeyError:

    print("Missing key!")

except TypeError:

    print("Type mismatch!")        

  • Catch different exceptions with different handlers.
  • Keep handlers specific, avoid a broad except Exception: unless absolutely necessary.


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()        

  • else runs only if no exception occurs.
  • finally always runs, making it perfect for cleanup tasks (like closing files or database connections).


Raising Exceptions

def divide(a: float, b: float) -> float:

    if b == 0:

        raise ZeroDivisionError("Cannot divide by zero.")

    return a / b        

  • Use raise to signal invalid states.
  • Raising exceptions makes your code fail fast and easier to debug.


Best Practices

  • Catch only the exceptions you expect and know how to handle.
  • Avoid swallowing errors silently.
  • Use custom exceptions for domain-specific errors:

class InsufficientBalanceError(Exception):

    pass        

  • Prefer with context managers (they handle cleanup automatically).


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


Bruno Fernandes Brugnhago

Fullstack Software Engineer | Java | Spring Boot | React | AWS | Docker | PostgreSQL

2d

Great 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.

Like
Reply
Jimmy Bastos

Software Engineer | Node | Typescript | React | AWS

3d

Thoughtful post, thanks Arthur

Like
Reply
Aleson França

Senior Software Engineer | PHP | Laravel | Node.js | NestJS | Go | Golang | Microservices | Docker | Kubernetes | GCP

3d

Thanks for sharing, Arthur

Like
Reply
Matheus Custódio

Senior .NET Software Engineer | Fullstack | C# | .NET | React | AWS | Azure

4d

Thanks for sharing, Arthur

Marcos Tupan

Senior Software Engineer | C# .NET | Fullstack

4d

Thoughtful post, thanks Arthur

To view or add a comment, sign in

Explore topics