Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use try, except, else correctly in Python

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.

like image 401
john.dou.2011 Avatar asked Nov 17 '12 18:11

john.dou.2011


People also ask

How do I use try except else in Python?

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.

Can we use else with except in Python?

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.

How do you define try and except in Python?

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.

Is it good to use try except Python?

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.


1 Answers

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.

like image 72
gnr Avatar answered Oct 03 '22 22:10

gnr