-9

My code works, but I am thinking there is something wrong with my understanding, or possibly (gasp) an error in Python's raise behavior.

I am looping over a set of arguments. I capture the first error and want to raise it after I have finished looping, with the original traceback etc as described in “Inner exception” (with traceback) in Python?

I obviously want the loop to process all the arguments, and only then tell me what went wrong.

error = None
for arg in arguments:
    try:
        process(arg)
    except ValueError, err:
        if not error:
            error = sys.exc_info()
if error:
    raise error[0], error[1], error[2]

The last line is the problematic line. It works (demo: http://ideone.com/HFZETm -- note how it prints the traceback from the first error, not the last one), but it seems extremely clunky. How could I express that more succinctly?

raise error would seem more elegant, but it behaves as if I had simply raise error[0] (or perhaps raise error[1]). raise *error is a syntax error.

Community
  • 1
  • 1
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 1
    In Python3, you can do `raise error[1].with_traceback(error[2])`. I don't know of an equivalent for Python 2, sadly. – pistache Aug 03 '16 at 11:06

1 Answers1

2

Maybe, you could just do this:

for arg in arguments:
    try:
        process(arg)
    except ValueError:
        raise

Also, if you're going to do this multiple times, you could just wrap it in a function:

def raise_error(err):
    raise err[0], err[1]. err[2]

error = None
for arg in arguments:
    try:
        process(arg)
    except ValueError, err:
        if not error:
            error = sys.exc_info()
if error:
    raise_error(error)
Julien Spronck
  • 15,069
  • 4
  • 47
  • 55
  • Huh? No, that would be the same as omitting the `try`/`except` and would cause processing to terminate at the first error. Clarified the question to emphasize that this is not acceptable. – tripleee Aug 03 '16 at 07:42
  • 1
    Julien, do you really need *two separate* answers to the same question? And they're even so similar... And one starts with "maybe, you could do this", the other "probably not what you're after". I suggest editing them into the same answer. – Andras Deak -- Слава Україні Aug 03 '16 at 09:55
  • 1
    @AndrasDeak I think that they are fundamentally different solutions but I don't mind regrouping them. – Julien Spronck Aug 03 '16 at 09:57
  • Copying my comment here from the deleted answer; I'm hoping for a way to pass the full argument list to `raise`. Your `raise_error` function is a good workaround for encapsulating away the ugliness, but it's still there inside the `def`; since my code only needs to do this once, the encapsulation doesn't really buy me anything. – tripleee Aug 03 '16 at 10:52