简体   繁体   中英

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.

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 .

If there is no error, then I get 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 .

How can I achieve that?

You need to define error_message before the try/catch block as you have already for 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.

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 . You should specify the type of exception you're getting or you risk catching others, like KeyboardInterrupt and SystemExit .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM