异常处理:多次处理异常

时间:2014-02-13 03:30:49

标签: python mysql exception mysql-python

我有一个python脚本,它从互联网上下载某些数据(从URL列表中)并将其存储在MySQL数据库中。我的代码是这样的:

try:
    con = mdb.connect(host = 'localhost', user = 'root', passwd = 'gatech', db ='SpecialProb', charset = 'utf8');
    cur = con.cursor()
    print " Database Connection Parameters set"
except mdb.Error, e:  
    print "Error %d: %s" % (e.args[0],e.args[1])
    sys.exit(1)
try:
    for item in listURLs[index:]:
        try:
            r2 = requests.get(item)
        except:
            print "Could not fetch data"
            print "Exception: ", sys.exc_info()[0]
            continue

         ## Some code to fetch Name, ID from the internet, which I have tested and which works correctly. ##
         try:
             cur.execute("INSERT into TABLENAME (NAME, ID" 
             ") VALUES (%s, %s)",
             (totalName, ID))

             print("Value inserted in database.\n")
             countInsert += 1;
             con.commit() 
         except mdb.IntegrityError:
             print "Most likely cause: Database already contains this entry."
             print "Message from system: "
             print "Error %d: %s\n" % (e.args[0],e.args[1])
             continue
except:
    print "'For loop exception: ", sys.exc_info()[0]        
    sys.exit(0)

我获取的数据可能是重复的,我不希望将重复数据插入到数据库中,代码应该在下一次迭代中蚀刻下一个数据而不是存储数据。所以我在那里有except mdb.IntegrityError:行来处理重复项。

但是,在捕获重复条目的异常之后,代码将转到我为except循环设置的for,而不是经过下一次迭代。 这是我得到的:

Most likely cause: Database already contains this entry. 
Message from system:
'For loop exception:  <type 'exceptions.NameError'>

为什么会这样?我该如何防止这种情况发生?

非常感谢!

1 个答案:

答案 0 :(得分:1)

您的e不会被定义,导致您的except块中出现异常。 像mdb.IntegrityError,e

一样使用except mdb.Error, e