簡體   English   中英

為什么在我的Python腳本的except子句中出現UnboundLocalError?

[英]Why am I getting an UnboundLocalError in the except clause of my Python script?

我有以下來自Python腳本的代碼部分。

status = 'success'
try:
 sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))
except Exception as e:
  #traceback.print_exc()
  error_message = e
#  print str(e)
  status = 'fail'
print ("{},{},{},{}".format(hivedb,table,status,error_message)) 
sys.exit(1)

在這部分代碼中,如果有exception那么我將設置error_message

如果沒有錯誤,那么我會得到UnboundLocalError: local variable 'e' referenced before assignment

我想要的是如果沒有錯誤,我希望將error_message設置為No error

我該如何實現?

您需要在try / catch塊之前定義error_message ,因為您已經具有status

status = 'success'
error_message = 'No error'
try:
    sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))
except Exception as e:
    error_message = e
    status = 'fail'

一種更清潔的方法是使用else ,因為狀態更新應該是原子的。

try:
    sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))
except Exception as e:
    status = 'fail'
    error_message = e
else:  # Executes only if no Exception.
    status = 'success'
    error_message = 'No error'

附帶說明一下,用except Exception進行全面的異常捕獲是一個壞主意。 您應該指定要獲取的異常類型,否則可能會捕獲其他異常,例如KeyboardInterruptSystemExit

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM