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.
The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks.
In the finally clause, you can specify the clean-up action to be executed whether an exception occurs or not. You can also use the else and finally clause together. If no exception occurs, the else clause is executed and then the finally clause is executed.
The Python try… except statement runs the code under the “try” statement. If this code does not execute successfully, the program will stop at the line that caused the error and the “except” code will run. The try block allows you to test a block of code for errors.
The reason to use try/except is when you have a code block to execute that will sometimes run correctly and sometimes not, depending on conditions you can't foresee at the time you're writing the code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With