« Learnt in London - Ruby, Martini, Coral and the Core | Main | Sending an email from Python »

January 18, 2007

Nested exceptions in Python

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.

Posted by gje at January 18, 2007 08:19 AM

Comments

Post a comment




Remember Me?


Well House Consultants Ltd. Copyright 2008