LSZ
LSZ

Reputation: 75

Why return in function suppress the exception raised?

Check the following code about exception processing in python

class myException(Exception):
    def __str__(self):
        return 'this is my exception'
class myException2(Exception):
    def __str__(self):
        return 'this is my exception 2'
def myfunc():
    try:
        raise myException2
        print('after exception')
    except myException:
        a = 'exception occur'
        print(a)
    else:
        a = 'exception doesn\'t occur'
        print(a)
    finally:
        a = 'no matter exception occurs or not'
        print(a)
        return a

Then runing myfunc() will output without any exception popping up

no matter exception occurs or not

But if the 'return a' code in finally clause in commented, the output will capture the unhandled myException2,

no matter exception occurs or not
---------------------------------------------------------------------------
myException2                              Traceback (most recent call last)
<ipython-input-140-29dfc9311b33> in <module>()
----> 1 myfunc()

<ipython-input-139-ba35768198b8> in myfunc()
      1 def myfunc():
      2     try:
----> 3         raise myException2
      4         print('after exception')
      5     except myException:

myException2: this is my exception 2

Why are the return code so important to do with the capturing of exception?

Upvotes: 3

Views: 171

Answers (1)

KillianDS
KillianDS

Reputation: 17186

Directly from the python docs:

If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception, it is re-raised at the end of the finally clause. If the finally clause raises another exception or executes a return or break statement, the saved exception is discarded:

This makes sense, because printing this error happens at the end of the finally statement. You explicitly exit the statement early, so that printing shouldn't be executed.

Upvotes: 5

Related Questions