Search code examples
pythonexceptionraise

How to report an exception for later


I have a python file in which i have two functions that each of them raise an exception.

def f():
    raise e1

def g():
    raise e2

My question, is it possible to store these exceptions in a variable, like list for example--[e1, e2]--, in order to control the order of exceptions execution in another function, say h ?


Solution

  • Exceptions are objects, like most things in Python; specifically, you can bind one to a name when you catch it, then add it to a list. For example:

    exceptions = []
    try:
        f()
    except Exception as f_exc:
        exceptions.append(f_exc)
    
    try:
        g()
    except Exception as g_exc:
        exceptions.append(g_exc)
    

    I'm not sure what use case you have in mind that you want to store exceptions to look at later. Typically, you act on an exception as soon as you catch it.