尝试...除外...除外...:如何避免重复代码 [英] try... except... except... : how to avoid repeating code

查看:90
本文介绍了尝试...除外...除外...:如何避免重复代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  • 我想避免在多个地方写入 errorCount + = 1

  • 我正在寻找比


    success = False
    try:
        ...
    else:
        success = True
    finally:
        if success:
            storage.store.commit()
        else:
            storage.store.rollback()




  • 我正在尝试避免 store.rollback()在每个except子句中。

    • I'm trying to avoid store.rollback() in every except clause.
    • 关于如何执行此操作的任何想法?

      Any idea on how to do this?

      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 语句的可能应用程序,它允许撤消操作并安全释放资源,无论结果是什么代码块

      This look like a possible application of Python's new with statement. It allows to to unwind operations and release resources securely no matter what outcome a block of code had.

      PEP 343

      这篇关于尝试...除外...除外...:如何避免重复代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆