[英]Why am I getting an UnboundLocalError in the except clause of my Python script?
I have the following part of code from a 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)
Here in this part of code, if there is an exception
then I am setting error_message
. 在这部分代码中,如果有
exception
那么我将设置error_message
。
If there is no error, then I get UnboundLocalError: local variable 'e' referenced before assignment
. 如果没有错误,那么我会得到
UnboundLocalError: local variable 'e' referenced before assignment
。
What I want is if there is no error, I want the error_message
set to No error
. 我想要的是如果没有错误,我希望将
error_message
设置为No error
。
How can I achieve that? 我该如何实现?
You need to define error_message
before the try/catch block as you have already for status
: 您需要在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'
A cleaner approach for this is to use an else
, since state updates should be atomic. 一种更清洁的方法是使用
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'
As a side note, it's a bad idea to do blanket exception-catching with except Exception
. 附带说明一下,用
except Exception
进行全面的异常捕获是一个坏主意。 You should specify the type of exception you're getting or you risk catching others, like KeyboardInterrupt
and SystemExit
. 您应该指定要获取的异常类型,否则可能会捕获其他异常,例如
KeyboardInterrupt
和SystemExit
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.