python错误检查
我正在使用下面的代码。如何添加错误检查。 如果有任何错误,请更换“继续读取” 例如:如果卷为N\a或缺少,请替换为“a值” 不要跳过这一行,不要停下来python错误检查,python,error-handling,Python,Error Handling,我正在使用下面的代码。如何添加错误检查。 如果有任何错误,请更换“继续读取” 例如:如果卷为N\a或缺少,请替换为“a值” 不要跳过这一行,不要停下来 reader = csv.reader(idata.split("\r\n")) stocks = [] for line in reader: if line == '': continue stock, price, volume, stime = line price = float(price)
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))
执行以下操作:
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"
基本上定义另一种方法(或内联执行)来验证股票、价格、数量和时间是否符合预期。如果您的float()或int()调用将price和volume字符串转换为其预期类型失败,我也会尝试在这里捕获任何错误。谢谢!我的想法是只有几张唱片会坏,还是会出错。我在想,如果体积是文本,返回int(0),如果价格是文本,返回float(0)