Handle generator exceptions in its consumer

前端 未结 8 1614
迷失自我
迷失自我 2020-11-29 10:07

This is a follow-up to Handle an exception thrown in a generator and discusses a more general problem.

I have a function that reads data in different formats. All fo

8条回答
  •  感情败类
    2020-11-29 10:42

    An example of a possible design:

    from StringIO import StringIO
    import csv
    
    blah = StringIO('this,is,1\nthis,is\n')
    
    def parse_csv(stream):
        for row in csv.reader(stream):
            try:
                yield int(row[2])
            except (IndexError, ValueError) as e:
                pass # don't yield but might need something
            # All others have to go up a level - so it wasn't parsable
            # So if it's an IOError you know why, but this needs to catch
            # exceptions potentially, just let the major ones propogate
    
    for record in parse_csv(blah):
        print record
    

提交回复
热议问题