Try ... except ... except ...: how to avoid code repeating

  • I would like to avoid writing errorCount += 1in several places.
  • I'm looking for a better way than
    success = False
    try:
        ...
    else:
        success = True
    finally:
        if success:
            storage.store.commit ()
        else:
            storage.store.rollback ()
  • I try to avoid store.rollback()except in every sentence.

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)
+3
source share
5 answers

This looks like a possible application of the new withPython operator . This allows you to quickly turn off operations and free up resources, regardless of what the result was a block of code.

PEP 343

+8

logError(), errorCount ( -) . , , :

try:
    # something
except (CustomerNotFoundError, ProductNotFoundError), e:
    logError(e)

, , e.

, : successCount = len(rows) - errorCount

+3

, , ( , , ), , (msg), , , . , , .

+2

If you like to cumulate errors, why don't you cumulate errors? If you put error messages in a list, the size of the list gives the information you need. You can even postprocess something. You can easily decide if an error has occurred and printing is only called in one place.

0
source

Well, according to this page, part 7.4:

http://docs.python.org/reference/compound_stmts.html

This is possible with python ver. > = 2.6. I mean try..except..finally construction.

0
source

Source: https://habr.com/ru/post/1708554/