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["itemCode"]
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 KeyError:
print "Bad parameter name"
except:
print "Unknow error"
Option 2
try:
itemCode = items["itemCode"]
except KeyError:
print "Bad parameter name"
else:
dbObject=db.GqlQuery("SELECT * FROM %s WHERE code=:1" % dbName,itemCode).get()
try:
dbObject.delete()
except AttributeError:
print "There's no item with that code"
except:
print "Unknow error"
Option 3 Any other better option you can think of.
Option 1, we see that I wrap all the code in a try block. Option 2, it uses nested blocks. It raises an exception on specific line statements.
If there's an error somewhere I will be glad to know about it.
try:block and theelse:block, am I missing something or does this not make sense?if dbObject is not None: dbObject.delete()instead of catching AttributeError here.