[英]How to handle exceptions in python using the `with` statement in python?
假設這段代碼:
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 x as y: z()
基本上是語法糖:
y = x
y.__enter__()
try:
z()
finally:
if y.__exit__: y.__exit__()
這並不完全准確,但這就是它的要點。 請注意,如果拋出異常(請參閱文檔),則__exit__()
將傳遞異常信息,因此您可以通過這種方式“處理”異常,但這不會阻止異常被拋出調用堆棧。
如果要優雅地處理異常並使用它,則需要使用try
/ catch
塊。 它可以在with
塊內部或外部,只要在引發異常時 try 塊處於活動狀態。
在oursql的特殊情況下,
with some_connection.cursor() as cursor:
do_something_with(cursor)
相當於
cursor = some_connection.cursor()
try:
do_something_with(cursor)
except:
some_connection.rollback()
raise
else:
some_connection.commit()
finally:
cursor.close()
如您所見, with
語句的作用取決於上下文管理器(例如 some_connection.cursor()`)。
with connection.cursor() as cursor:
try:
cursor.execute('some query')
except IntegrityError as e:
# handle exception
可能是也可能不是處理IntegrityError
的正確方法——您可能希望在某些外部 scope 中處理 IntegrityError。
例如,如果您有一些通用的 function 記錄查詢,例如
def log_query(query):
logger.info(query)
with connection.cursor() as cursor:
cursor.execute(query)
try:
log_query(query)
except IntegrityError as err:
# handler error
您可能不想在 log_query 中處理IntegrityError
,而是在稍后階段處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.