Merlin
Merlin

Reputation: 25639

python error checking

I am using code below. How Do add error checking. If anything is error, replace continue reading Ex: if volume is N\a or missing , replace with 'a value.' Don't skip line, don't stop.

reader = csv.reader(idata.split("\r\n"))

stocks = []
for line in reader:
    if line == '':
        continue

    stock, price, volume, stime = line
    price = float(price)
    volume = int(volume)

    stocks.append((stock, price, volume, stime))

Upvotes: 2

Views: 565

Answers (1)

whaley
whaley

Reputation: 16265

Do something like the following:

def isRecordValid(stock,price,volume,stime):
    #do input validation here, return True if record is fine, False if not.  Optionally raise an Error here and catch it in your loop
    return True

reader = csv.reader(idata.split("\r\n"))

stocks = []
for line in reader:
    if line == '':
        continue

    stock, price, volume, stime = line
    try:
        if isRecordValid(stock,price,volume,stime):
            price = float(price)
            volume = int(volume)
            stocks.append((stock, price, volume, stime))
        except Exception as e:
            print "either print or log and error here, using 'except' means you can continue execution without the exception terminating your current stack frame and being thrown further up"

Basically define another method (or do it inline) to validate that stock, price, volume, and stime are all as you expect it. I'd try to catch any Errors here too in case your float() or int() calls to convert the price and volume strings to their expected types fails for whatever reason.

Upvotes: 2

Related Questions