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?
The Usual Solution: . If the KeyError is raised from a failed dictionary key lookup in your own code, you can use . get() to return either the value found at the specified key or a default value.
A Python KeyError is raised when you try to access an item in a dictionary that does not exist. You can fix this error by modifying your program to select an item from a dictionary that does exist. Or you can handle this error by checking if a key exists first.
Avoiding KeyError when accessing Dictionary Key We can avoid KeyError by using get() function to access the key value. If the key is missing, None is returned. We can also specify a default value to return when the key is missing.
The Python "KeyError: 2" exception is caused when we try to access a 2 key in a a dictionary that doesn't contain the key. To solve the error, set the key in the dictionary before trying to access it or conditionally set it if it doesn't exist.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With