Catch KeyError in Python

If it's raising a KeyError with no message, then it won't print anything. If you do...

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

...you'll at least get the exception class name.

A better alternative is to use multiple except blocks, and only 'catch' the exceptions you intend to handle...

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

There are valid reasons to catch all exceptions, but you should almost always re-raise them if you do...

try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print 'I got a KeyError - reason "%s"' % str(e)
except:
    print 'I got another exception, but I should re-raise'
    raise

...because you probably don't want to handle KeyboardInterrupt if the user presses CTRL-C, nor SystemExit if the try-block calls sys.exit().


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)