[python] Catch KeyError in Python

If I run the code:

connection = manager.connect("I2Cx")

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

But if I do:

try:
    connection = manager.connect("I2Cx")
except Exception, 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?

This question is related to python try-catch except

The answer is


You should consult the documentation of whatever library is throwing the exception, to see how to get an error message out of its exceptions.

Alternatively, a good way to debug this kind of thing is to say:

except Exception, e:
    print dir(e)

to see what properties e has - you'll probably find it has a message property or similar.


You can also try to use get(), for example:

connection = manager.connect.get("I2Cx")

which won't raise a KeyError in case the key doesn't exist.

You may also use second argument to specify the default value, if the key is not present.


I am using Python 3.6 and using a comma between Exception and e does not work. I need to use the following syntax (just for anyone wondering)

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

If you don't want to handle error just NoneType and use get() e.g.:

manager.connect.get("")

Try print(e.message) this should be able to print your exception.

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

I dont think python has a catch :)

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