繁体   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