Python try/expect code shows `local variable referenced before assignment` error

Viewed 32

I added this code here meant for error handling:

try:
    music = session.query(Music).filter_by(Assetid=id).one()
    music.firstname = new_AssetName
    music.lastname = new_category
    music.DOB = new_borrower
    music.experience = new_status
    music.experience = new_value
    session.commit()
except Exception as e:
   message = "Error updating player:" + e.toString()  
finally:
    return template('success.tpl', message=message)

and it keeps on giving me the error

UnboundLocalError: local variable 'message' referenced before assignment

I tried to make message a global variable so like:

except Exception as e:
   global message
   message = "Error updating player:" + e.toString() 

But this just gives me an error saying that message is not defined. I am quite lost on how to fix this any help would be great

1 Answers

The message variable is not defined in your try block. This means that when your code gets to the finally block, if the execution didn't raise an exception the message variable will be undefined and therefore raise the UnboundLocalError exception.

To solve this, you could simply do:

try:
    music = session.query(Music).filter_by(Assetid=id).one()
    music.firstname = new_AssetName
    music.lastname = new_category
    music.DOB = new_borrower
    music.experience = new_status
    music.experience = new_value
    session.commit()
    message = "Successfully updated player"

except Exception as e:
    message = f"Error updating player: {e}"

finally:
    return template("success.tpl", message=message)
Related