异常处理:多次处理异常
问题描述:
我有一个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'>
为什么会出现这种情况?我如何防止发生这种情况?
非常感谢!
答
您的e将不会被定义在您的except块中导致异常。 使用mdb.IntegrityError,e
像你这样做except mdb.Error, e
+0
谢谢!这解决了它! :-) – TheRookierLearner
请问1)修复缩进,2)发布你得到的实际例外? – thefourtheye
另外,不要打开每个项目的连接,也不要创建一个'listURLs [index:]'副本。 – thefourtheye
@thefourtheye - 完成。 – TheRookierLearner