Main Content

Nested exceptions in Python

Archive - Originally posted on "The Horse's Mouth" - 2007-01-18 08:19:39 - Graham Ellis

Yes, you can nest exceptions in Python - here's an example from yesterday's course.

I'm reading in lines from a data file and counting the numbe of occurrences of a particular series of events in a dictionary of dictionaries.

An exception is thrown if a counter doesn't already exist ... we'll catch that and create the extra counter if we have to ... excpet that ...

The incoming data line may be a short header, in which case we ignore it.

Here's the code:

import urllib

fh = urllib.urlopen("http://192.168.200.67/data/access_log.xyz")
counter = {}
goofs = 0

while 1:
  line = fh.readline()
  if not line: break
  hinfo = line.split(" ")
  try:
    counter[hinfo[6]][hinfo[0]] += 1
  except:
    try:
      counter[hinfo[6]] = {}
      counter[hinfo[6]][hinfo[0]] = 1
    except:
      pass
print counter
print "problem count =",goofs


Remember that in Python, you inset code to indicate your block structure, and that the pass statement can be used to create a do-nothing block.