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 ?

codeforester
  • 39,467
  • 16
  • 112
  • 140
LChampo
  • 77
  • 1
  • 8
  • 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. – Reut Sharabani Jul 31 '18 at 13:09
  • 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... – LChampo Jul 31 '18 at 21:02

2 Answers2

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
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())
Schwefelhexa
  • 94
  • 2
  • 9