[英]Where and how to insert 'try and except' in this code to avoid program crash?
[英]try… except… except… : how to avoid repeating code
errorCount += 1
。 success = False try: ... else: success = True finally: if success: storage.store.commit() else: storage.store.rollback()
store.rollback()
。 有关如何做到这一点的任何想法?
count = 0
successCount = 0
errorCount = 0
for row in rows:
success = False
count += 1
newOrder = storage.RepeatedOrder()
storage.store.add(newOrder)
try:
try:
newOrder.customer = customers[row.customer_id]
except KeyError:
raise CustomerNotFoundError, (row.customer_id,)
newOrder.nextDate = dates[row.weekday]
_fillOrder(newOrder, row.id)
except CustomerNotFoundError as e:
errorCount += 1
print u"Error: Customer not found. order_id: {0}, customer_id: {1}".format(row.id, e.id)
except ProductNotFoundError as e:
errorCount += 1
print u"Error: Product not found. order_id: {0}, product_id: {1}".format(row.id, e.id)
else:
success = True
successCount += 1
finally:
if success:
storage.store.commit()
else:
storage.store.rollback()
print u"{0} of {1} repeated orders imported. {2} error(s).".format(successCount, count, errorCount)
这看起来像Python的新的可能的应用with
声明。 它允许解除操作并安全地释放资源,无论代码块有什么结果。
在PEP 343中了解它
我的建议是写一个errorCount
logError()
方法,增加errorCount
(使它成为一个成员变量)并打印错误。 由于您的异常代码类似,您还可以通过执行以下操作来缩短代码:
try:
# something
except (CustomerNotFoundError, ProductNotFoundError), e:
logError(e)
您可以根据e
打印任何您想要的内容。
此外,您不需要跟踪成功: successCount = len(rows) - errorCount
您可以简单地将异常实现包装在特定于异常的容器类中,这样您也可以避免所有这些显式的打印调用(一旦您更改了界面,这可能会派上用场,例如在支持GUI时),而您将拥有像错误(msg)这样的方法,反过来可以在内部相应地增加错误计数。 换句话说,只需设置一个外部帮助程序类来管理异常处理。
如果你喜欢累积错误,为什么你不累积错误? 如果将错误消息放在列表中,列表的大小将提供所需的信息。 你甚至可以对事物进行后处理。 如果发生错误并且仅在一个地方调用打印,您可以轻松决定
那么,根据这个页面,第7.4部分:
http://docs.python.org/reference/compound_stmts.html
这可以使用python ver。 > = 2.6。 我的意思是try ..except..finally建设。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.