How do I catch a KeyError in Python?

How do I catch a KeyError in Python?

When I run this code:

connection = manager.connect("I2Cx")

The program crashes and reports a KeyError because "I2Cx" doesn’t exist (it should be "I2C").

But when I do this:

try:
    connection = manager.connect("I2Cx")
except Exception as e:
    print(e)

It doesn’t print anything for e. I would like to be able to print the exception that was thrown. If I try the same thing with a divide by zero operation, it is caught and reported properly in both cases. What am I missing here?

If you’re encountering a KeyError with no message, you might want to ensure it actually prints something useful. A simple way to do that is by using repr() to get a full representation of the exception:

try:
    connection = manager.connect("I2Cx")
except Exception as e:
    print(repr(e))

This will give you the exception class name along with the actual error message, which is super helpful for debugging.

That’s a good start, but catching exceptions in a more structured way is even better. Instead of a generic except Exception, handling specific exceptions like KeyError and IndexError makes your code more readable and avoids masking unexpected issues:

try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print(f'I got a KeyError - reason "{str(e)}"')
except IndexError as e:
    print(f'I got an IndexError - reason "{str(e)}"')

This way, you’re explicitly handling different errors separately, which makes debugging easier and keeps your error handling clean.

Right, and if you need to catch all exceptions for logging or cleanup, it’s still a good practice to re-raise unexpected ones. Otherwise, you might accidentally swallow something critical like a KeyboardInterrupt. Here’s how you can do it properly:

try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print(f'I got a KeyError - reason "{str(e)}"')
except Exception as e:
    print(f'I got another exception: {repr(e)}. Re-raising it!')
    raise

This ensures that while you handle known errors, unexpected ones don’t get silently ignored, which can save you from nasty debugging surprises later on.