17

Consider the following code:

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

    if __name__ == "__main__":
        try:
            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?

graceshirts
  • 339
  • 1
  • 2
  • 6
  • 5
    Do you know what `return` does? I recommend the [official Python tutorial](https://docs.python.org/3.5/tutorial/index.html). – TigerhawkT3 Oct 29 '16 at 03:57
  • 1
    This question does not show a reasonable amount of research about frankly elementary concepts in Python (and in programming in general). I don't believe this is a good contribution to StackOverflow, and I'm voting to close as "too broad." – Jules Oct 29 '16 at 05:33
  • 8
    @Jules He could have formulated it in a better way but I think the fundamental question, which leis at the root here, is a good one. Therefore this question doesn't deserve a negative score IMO. – Elmex80s Oct 18 '17 at 09:46
  • 6
    It's a reasonable question - how are you going to learn if you can't ask questions? – jouell Mar 13 '21 at 03:56

1 Answers1

29

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.

try:
    if something_bad:
        raise generate_exception()
except CertainException, e:
    do_something_to_handle_exception(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.

Ziyad Edher
  • 2,100
  • 18
  • 31