You’ve likely encountered errors in your programming journey such as IndexError, KeyError and ValueError.

Knowing how to handle these properly in your code so that these errors don’t show up in production is essential to being able to write clean, efficient code.

To handle errors effectively, you’ll leverage the try/except keywords.

An Example of Error Handling

Take this snippet of what seems to be clean code:

def fetch_user_score(data, user_id):
    return int(data[user_id]["score"])

It looks okay because you’re assuming that user_id is in the dictionary and that score is in there, and casting it to an integer. But what if score isn’t in the dictionary?

We can handle it using try/except:

def fetch_user_score(data: dict, user_id: int):
    try:
        return int(data[user_id]["score"])
    except:
        return f"Score not found for user ID: {user_id}"

While this is acceptable for handling errors, one major fundamental (and non-best practice) issue is that this handles every single error that can be thrown.

» For more information on this topic, check out The Dangers of Overgeneralizing Exceptions.

Instead, we’re going to want to try and identify what errors can be raised and then identify how we want to handle it.

Looking at the code, there’s 4 errors that can be raised:

  1. TypeError: score is either None or a list.

  2. ValueError: score is “NA” or “bad”.

  3. 2 KeyError: user_id is missing or score is missing.

To fix this, we’ll modify our try/except statement appropriately:

def fetch_user_score(data, user_id):
    try:
        return int(data[user_id]["score"])
    except KeyError:
        return 0  # Default score if missing
    except (TypeError, ValueError):
        return -1  # Invalid score format

From here, we can insert logging statements and other logic to be able to handle the cases where these errors can be thrown.

Best Practices to Handle Errors

  1. Catch only what you can handle. Don’t catch exceptions unless you can meaningfully recover from them.

  2. Be specific. Use the most specific exception type possible.

  3. Avoid bare try/except statements. These catch everything, including KeyboardInterrupt

  4. Don’t silence errors. If something must be silenced, leave at least a comment explaining why.

Commonly used Exceptions

There’s an overwhelmingly high amount of exceptions that Python can throw. To help alleviate this, I’ve included a table of the most commonly used exceptions that Python gives you:

Exception

When to use it

AttributeError

Calling a method or attribute that doesn’t exist on an object.

FileNotFoundError

Missing file in open(), os, or path-related operations.

ImportError

Base exception for failed imports: dynamic imports, optional deps, etc.

IndexError

Accessing a list or tuple index that doesn’t exist.

KeyError

Dict key lookup failed (e.g., my_dict["missing_key"])

OSError

OS-level failure; disk full, permission denied, file busy, etc.

RuntimeError

Generic error; use when no other specific exception fits.

TypeError

Invalid operation between mismatched types (e.g., str + int).

ValueError

Right type, wrong content (e.g., int("abc"), math domain errors)

Happy coding!

📧 Join the Python Snacks Newsletter! 🐍

Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:

  1. Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.

  2. Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.

  3. Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.

You can unsubscribe at any time.

Interested in starting a newsletter or a blog?

Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.

If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.

This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.

Reply

or to participate

Keep Reading

No posts found