Search code examples
pythonerror-handlingtry-excepterror-code

Return Error code when using try and except? (without raise)


I have some scripts running in docker containers that collect data from yfinance. Sometimes crashes occur because the data is not available.

So I wanted to send me a mail if a crash occurs in a script, but I wanted it to be the exact error code that caused the main function to crash.

Is there a way that would allow me to return the exact error code as a variable (and send it per mail) instead of just using try and except?

if __name__ == '__main__':
    try:
        main()
    except:
        ERROR = 'Value Error occured in BOT1'
        print(ERROR)
        sendmail(ERROR)
        sleep_time(1800)

Solution

  • [...] but I wanted it to be the exact error code that caused the main function to crash.

    Try with the except/as syntax:

    try:
        main()
    except Exception as e:
        # here you can print e