Search code examples
pythonexcept

Catch anything and save it into a variable


I'm wondering if there is a keyword for "all" in python except. I've ran into this seemingly simple problem:

try:
    #do stuff
except any as error:
    print('error: {err}'.format(err=error))

I know that you can do except: to catch all errors, but I don't know how to add an as keyword to get a printable object. I want to catch any error and be able to get an object for use in printing or something else.


Solution

  • You can catch almost anything this way:

    try:
        #do stuff
    except Exception as error:
        print('error: {err}'.format(err=error))
    

    But to catch really everything, you can do this:

    import sys
    
    try:
        #do stuff
    except:
        err_type, error, traceback = sys.exc_info()
        print('error: {err}'.format(err=error))