0

I am trying to pass a specific key error.by this two.

try:    
    per_visit_large_store = 100 * dic_data[mac]['Retail Store']['No. of visit to large store']/float(dic_data[mac]['Total no. of walk_in'])
except KeyError: 'Retail Store'
    pass

and

try:    
    per_visit_large_store = 100 * dic_data[mac]['Retail Store']['No. of visit to large store']/float(dic_data[mac]['Total no. of walk_in'])
except KeyError: 'Retail Store':
    pass

both of this raises Indentation and syntax error respectively. What exactly I am doing wrong? I am using python 2.7

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82

2 Answers2

0

The correct syntax is:

try:
    ...
except KeyError:
    pass

If you want to catch a specific key then you need to check the message of the error:

d = {'a':1, 'b':2}
try:
    d['c']
except KeyError as e:
    if e.message == 'c':
        blah
    else:
        raise KeyError, e

This will only continue the code if the key is 'c'. If it is not, then the error is raised.

TerryA
  • 58,805
  • 11
  • 114
  • 143
0

Syntax is incorrect, it should be:

try:
    # some code there
except KeyError as e:
    caused_key = e.args[0]
    if caused_key == 'Retail Store':
        pass

See more in Python Exception tutorial

Good Luck :)!

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82