Python Key Error Exception
Contents |
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the python exceptions list company Business Learn more about hiring developers or posting ads with us Stack Overflow python filenotfounderror Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 6.2
Python Custom Exception
million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up Catch KeyError in Python up vote 9 down vote favorite 3 If I run the code: connection = manager.connect("I2Cx")
Python Exception Message
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? python valueerror example python try-catch except share|improve this question edited Apr 22 '13 at 18:36 asked Apr 22 '13 at 18:23 spizzak 2471512 4 Side note: Unless you need pre-2.5 compatibility, you should write except Exception as e: instead of except Exception, e:. –abarnert Apr 22 '13 at 18:47 add a comment| 4 Answers 4 active oldest votes up vote 18 down vote 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, 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, e: print 'I got a KeyError - reason "%s"' % str(e) except IndexError, 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, 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(). share|improve this answer edited Apr 22 '13 at
Rename Page Delete Page ------------------------ ------------------------ Remove Spam Revert
Python Exception Class Methods
to this revision ------------------------ SlideShow User python errno Login Python raises a KeyError whenever a dict() object is python attributeerror object has no attribute requested (using the format a = adict[key]) and the key is not in the dictionary. If you http://stackoverflow.com/questions/16154032/catch-keyerror-in-python don't want to have an exception but would rather a default value used instead, you can use the get() method: 1 default = 'Scruffy' 2 a = adict.get('dogname', default) Even more handy https://wiki.python.org/moin/KeyError is somewhat controversially-named setdefault(key, val) which sets the value of the key only if it is not already in the dict, and returns that value in any case: 1 default = 'Scruffy' 2 dog_owned_by = {'Peter': 'Furry', 'Sally': 'Fluffy'} 3 4 dogs = [] 5 for owner in ('Peter', 'Sally', 'Tim'): 6 dogs.append(dog_owned_by.setdefault(owner, default)) 7 8 # dogs == ['Furry', 'Fluffy', 'Scruffy'] 9 # dog_owned_by == {'Tim': 'Scruffy', 'Peter': 'Furry', 'Sally': 'Fluffy'} KeyError (last edited 2012-11-20 14:56:07 by yosefcz) MoinMoin PoweredPython PoweredGPL licensedValid HTML 4.01 Unable to edit the page? See the FrontPage for instructions.
tour help Tour Start here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta http://programmers.stackexchange.com/questions/225238/python-if-foo-in-dict-vs-try-dictfoo Discuss the workings and policies of this site About Us Learn http://www.java2s.com/Tutorial/Python/0060__Statement/CatchKeyErrorandAssertionError.htm more about Stack Overflow the company Business Learn more about hiring developers or posting ads with us Software Engineering Questions Tags Users Badges Unanswered Ask Question _ Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems python exception development life cycle who care about creating, delivering, and maintaining software responsibly. Join them; it only takes a minute: Sign up Here's how it works: Anybody can ask a question Anybody can answer The best answers are voted up and rise to the top Python - 'if foo in dict' vs 'try: dict[foo]' up vote 15 down vote python key error favorite 2 This is less a question about the nature of duck typing and more about staying pythonic, I suppose. First of all - when dealing with dicts, in particular when the structure of the dict is fairly predictable and a given key is not typically present but sometimes is, I first think of two approaches: if myKey in dict: do_some_work(dict[myKey]) else: pass And of course Ye Olde 'forgiveness vs permission' approach. try: do_some_work(dict[myKey]) except KeyError: pass As a journeyman Python guy, I feel like I see the latter preferred a lot, which only feels odd I guess because in the Python docs try/excepts seem to be preferred when there is an actual mistake, as opposed to an, um… absence of success? If the occasional dict does not have key in myDict, and it is known that it will not always have that key, is a try/except contextually misleading? This isn't a programming error, it's just a fact of the data - this dict just didn't have that particular key. This see
: except«Statement«Python TutorialPython TutorialStatementexceptimport sys, string matrix = {"brazil":"br","france":"fr","argentina":"ar","usa":"us"} def getcode(country): try: data = matrix[string.lower(country)] assert data != "br", "You cannot select this country for this action!" return data except KeyError: print sys.exc_type, ":", "%s is not in the list." % sys.exc_value print except AssertionError, b: print b print while 1: country = raw_input("Enter the country name or press x to exit: ") if country == "x": break code = getcode(country) if code != None: print "%s's country code is %s" % (country, code) print 3.10.except3.10.1.Catching Two Exceptions3.10.2.Simple exception handling example.3.10.3.Demonstrating exception arguments and stack unwinding.3.10.4.Catch more than on exceptions3.10.5.Catch KeyError and AssertionError3.10.6.try/except block that checks for correct user input3.10.7.try/except block with string argumentjava2s.com |Email:info at java2s.com|© Demo Source and Support. All rights reserved.