How to use try, except, else correctly in Python

前端 未结 3 2052
囚心锁ツ
囚心锁ツ 2021-01-04 04:10

So I want to know which is the right way to write try except statements. I\'m new to error handling in Python.

Option 1

try:
    itemCode = items[\"i         


        
相关标签:
3条回答
  • 2021-01-04 04:29

    Instead of catching KeyError, I prefer using get method of dicts with validation.

    itemCode = items.get("itemCode") # itemCode will be None, if no such key
    if itemCode is not None:
        print "code missing"
    

    This is not "general" solution (see comments to my answer), but in this case it'll help.

    And in first case I don't understand, why you trying to delete two times.

    try:
        itemCode = items.get("itemCode") # itemCode will be None, if no such key
        if itemCode is not None:
            print "code missing"
        dbObject=db.GqlQuery("SELECT * FROM %s WHERE code=:1" % dbName,itemCode).get()
        dbObject.delete() 
    except AttributeError:
        print "There's no item with that code"
    except StandardError as ex:    # good idea to be prepared to handle various fails
        print "Unexpected error deleting item {}".format(ex)
    

    And also, don't forget that python have finally section. It's oftem comes in handy sometimes.

    0 讨论(0)
  • 2021-01-04 04:34

    Simple - it depends. If you are certain about what exceptions you're going to get, you can stick with 1) and frankly, it is the case 90% of the time. The second way is useful if you know that many code routines can raise the same exception type.

    0 讨论(0)
  • 2021-01-04 04:41

    From the zen of python, "flat is better than nested." I'd go with Option #1 style in general, though I'm a bit confused as to whether dbObject=db.GqlQuery("SELECT.... or dbObject.delete() raises an AttributeError. In any case though, you shouldn't have to call the dbObject.delete() more than once.

    0 讨论(0)
提交回复
热议问题