Python 错误检查
我正在使用下面的代码。请问我该如何添加错误检查呢?
如果出现任何错误,就把“继续阅读”替换掉。
比如说,如果音量是N\a或者缺失,就用“一个值”来替换。
不要跳过这一行,也不要停止执行。
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))
1 个回答
2
可以像下面这样做:
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"
基本上,你需要定义另一个方法(或者直接在这里写)来检查股票、价格、交易量和时间是否都是你预期的那样。我建议在这里也捕捉任何错误,以防你在把价格和交易量的字符串转换成浮点数或整数时出现问题。