How to report an exception for later
Asked Answered
V

2

5

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 ?

Vienna answered 31/7, 2018 at 13:6 Comment(2)
Exceptions are something wrong that happened. They break the execution flow by jumping to the nearest except to respond immediately. I'm not sure you're using them correctly.Patrizius
U right @ReutSharabani. But in my case i am implementing an interpreter for some language and when i test it, i have noted that it is last wrong something which is raised first before the very first wrong one. The reason to it is, the tool i use to build the interpreter is of type LALR (Look-Ahead Left Right). Here is why i want to control exceptions...Vienna
G
11

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.

Guntar answered 31/7, 2018 at 13:8 Comment(2)
I learned something @chepner, thanks. Would logging be a preferred option to record exceptions?Patton
Thx for ur help. It is exactly what i needVienna
V
1

As chepner pointed out, exceptions are objects. If you later want to handle them in the same order (maybe even a different Thread), you should store them in a queue:

import Queue

exceptions = Queue.Queue()

try:
    f()
except Exception as e:
    exceptions.put(e)

You could then have another thread accessing the same variable exceptions and handle (or log) them:

while True:
    while not exceptions.empty():
        do_sth_with_exception(exceptions.get())
Viand answered 31/7, 2018 at 13:21 Comment(2)
Why a queue instead of a regular list?Podiatry
Queues are way more resource-efficient. Also, they have easy-to-use, threadsafe implementations.Viand

© 2022 - 2024 — McMap. All rights reserved.