Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between return and raise an Exception?

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?

like image 799
graceshirts Avatar asked Oct 29 '16 03:10

graceshirts


People also ask

What is difference between return and raise?

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 .

Which is better a return code or an exception?

An application that uses exceptions is more robust than an application that uses return codes. An application that uses exceptions can also give the cleanest code, since return codes don't have to be checked after every call.

What does it mean to raise an exception?

Raising an exception is a technique for interrupting the normal flow of execution in a program, signaling that some exceptional circumstance has arisen, and returning directly to an enclosing part of the program that was designated to react to that circumstance.

What is the difference between raising an exception and handling an exception?

Raise Exception is when you find an error and want to raise it. Exception handler is to catch exceptions raised by you or the system and handle them gracefully.


1 Answers

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.

like image 192
Ziyad Edher Avatar answered Oct 11 '22 16:10

Ziyad Edher