graceshirts graceshirts - 1 year ago 67
Python Question

Is there any difference between return and raise an Exception?

Consider the following code:

def f(x):
if x < 10:
return Exception("error")
raise Exception("error2")

if __name__ == "__main__":
f(5) # f(20)
except Exception:
print str(Exception)

Is there any difference?
When should I use return Exception and When should I use raise?

Answer Source

raise and return are two inherently different keywords.

raise, commonly known as throw in other languages, produces an error in the current level of the call-stack. You can catch a raised error by covering the area where the error might be raised in a try and handling that error in an except.

    if something_bad:
        raise generate_exception()
except CertainException, e:

return on the other hand, returns a value to where the function was called from, so returning an exception usually is not the functionality you are looking for in a situation like this, since the exception itself is not the thing triggering the except it is instead the raiseing of the exception that triggers it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download