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'
nev
  • 19
  • 2

2 Answers2

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)

wim
  • 338,267
  • 99
  • 616
  • 750
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'
Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
  • 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'] – Kasisnu Jul 24 '14 at 11:23
  • 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: http://stackoverflow.com/questions/17015230/are-nested-try-except-blocks-in-python-a-good-programming-practice – Anthony Kong Jul 24 '14 at 12:30