假定這一段代碼:如何在python中使用`with`語句處理異常?
connection = get_some_connection() # maybe from oursql
with connection.cursor() as cursor:
cursor.execute('some query')
據我所知,整理後cursor.close()
將自動執行。例外情況如何?我必須把它們放進去嗎?
connection = get_some_connection() # maybe from oursql
with connection.cursor() as cursor:
try:
cursor.execute('some query')
except IntegrityError, e:
# handle exceoption
還是有更好的方法來處理它們與with語句?
由於異常是如何傳播的,您是否也可以不在''with'塊之外立即**'try' /'catch'? ;) –
是的,絕對。我會更新我的答案,以便更清楚。 – cdhowie