How to return a value and raise an Exception

misterbear picture misterbear · Jan 21, 2014 · Viewed 24.9k times · Source

I have two objectives with this try/except statement.

  1. It needs to return a value of 1 if no problems occurred, or 0 if any problems occurred.
  2. It needs to raise an exception and end the script.

I have the return value working. I also have the SystemExit() working. But together, they aren't working.

My Python Script (that's relevant):

except IOError:
    value_to_return = 0
    return value_to_return
    raise SystemExit("FOOBAR")

With this, it ignores the raise SystemExit("FOOBAR") line completely. How do I go about getting a returned value and still raise SystemExit("FOOBAR")? This may be elementary to some, but I'm actually having quite a bit of difficulty with it.

Answer

user2357112 supports Monica picture user2357112 supports Monica · Jan 21, 2014

Returning and raising are mutually exclusive.

Raising SystemExit will end the script. A few cleanup routines get to run, and if the caller really, really wants to, they can catch the SystemExit and cancel it, but mostly, you can think of it as stopping execution right there. The caller will never get a chance to see a return value or do anything meaningful with it.

Returning means you want the script to continue. Continuing might mean having the caller raise SystemExit, or it might mean ignoring the error, or it might mean something else. Whatever it means is up to you, as you're the one writing the code.

Finally, are you sure you should be handling this error at all? Catching an exception only to turn it into a system shutdown may not be the most useful behavior. It's not a user-friendly way to deal with problems, and it hides all the useful debugging information you'd get from a stack trace.