Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a value and raise an Exception

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.

like image 889
misterbear Avatar asked Jan 21 '14 00:01

misterbear


People also ask

Can you throw an exception and return a value?

It's not possible to both throw an exception and return a value from a single function call.

Does raising an exception return?

Raising an exception terminates the flow of your program, allowing the exception to bubble up the call stack.

Can you raise and return Python?

You can't raise and return , but you could return multiple values, where the first is the same as what you're currently using, and the second indicates if an exception arose return True, sys. exc_info() == (None, None, None) or something similar but better suited to context.


2 Answers

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.

like image 125
user2357112 supports Monica Avatar answered Oct 09 '22 23:10

user2357112 supports Monica


You can raise an error with a 'returning_value' argument to be used after the calling.

Another pythonic answer to your problem could be to make use of the error arguments in the raise and then, in your call manage the error to get the value, convert it from string and get your 'return-ish'.

def your_f():
    try:
      some_io_thingy_ok()
      return 1
    except IOError:
        raise SystemExit("FOOBAR", 0)

try:
    my_returning_value = your_f()
except SystemExit as err:
    my_returning_value = err.args[1]


print(my_returning_value)

From Python 3 docs :

When an exception occurs, it may have an associated value, also known as the exception’s argument. The presence and type of the argument depend on the exception type.

The except clause may specify a variable after the exception name. The variable is bound to an exception instance with the arguments stored in instance.args. For convenience, the exception instance defines str() so the arguments can be printed directly without having to reference .args. One may also instantiate an exception first before raising it and add any attributes to it as desired.

like image 29
Natacha Avatar answered Oct 09 '22 23:10

Natacha