1

I get this error when I try to catch a KeyError twice. Is there anything in python which prevents you trying to catch the same error twice?

$ ./scratch.py
try getting a
can't get a try getting b
Traceback (most recent call last):
  File "./scratch.py", line 13, in <module>
    print dict['b']
KeyError: 'b'

The simplified code is below

dict={}
dict['c'] = '3'

try:
        print 'try getting a'
        print dict['a']
except KeyError:
        print 'can\'t get a try getting b'
        print dict['b']
except:
        print 'can\'t get a or b'
2
  • why not use dict.get? you also don't have the print dict['b'] in a try. Commented Jul 24, 2014 at 10:34
  • Hi Padriac- dict.get doesn't seem to throw an exception and fails silently? I would like to do something if I can't get a key. Commented Jul 24, 2014 at 11:42

2 Answers 2

2

I would do this with a simple for loop:

>>> d = {'c': 1}
>>> keys = ['a', 'b', 'c']
>>> for key in keys:
...     try:
...         value = d[key]
...         break
...     except KeyError:
...         pass
... else:
...     raise KeyError('not any of keys in dict')
... 
>>> value
1
>>> key
'c'

If you want to do it in one line:

key, value = next((k, d[k]) for k in keys if k in d)

Sign up to request clarification or add additional context in comments.

Comments

0

You need an extra try...except:

dict={}
dict['c'] = '3'

try:
        print 'try getting a'
        print dict['a']
except KeyError:
        print 'can\'t get a try getting b'
        try:
            print dict['b']
        except KeyError as e:
            print "Got another exception", e
except:
        print 'can\'t get a or b'

2 Comments

I don't think the indent is right for the second try, logically. Because if dict['a'] exists, there is no error and it never tries to check for dict['b']
I believe @nev is using the code snippet to understand the python exception handling mechanism. The key point I want to make is: if you want to handle an exception thrown within an exception handler, you need to add another try...except block. Here is a similar question in OS: stackoverflow.com/questions/17015230/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.