简体   繁体   中英

Why isn't my Python exception being re-raised?

I have a function within a module, that does something like this:

def some_func():

    try:
        # do some error-prone thing
        raise ValueError
        return 'calculated foo'
    except AttributeError as err:
        # handle it
        pass
    except:
        print('Some other error happened, let\'s reraise it....')
        raise
    else:
        pass
    finally:
        return 'default foo'

Then within my main program,

try:
    val = some_func()
    print('val=', val)
except:
    print('In main except')
    raise
else:
    print('In main else')
    pass
finally:
    print('And we\'re done')

My output is:

Some other error happened, let's reraise it....

val= default foo

In main else

And we're done

No exception is raised.

At the risk of missing something obvious, why isn't the ValueError being reraised within my main? It almost seems like the return within my finally in some_func() is causing the exception not to be reraised, but this seems odd to me and I can't find any documentation of it. Here's what I think should be happpening, would like to understand where I'm off.

  1. I call some_func() within my main program
  2. some_func() raises ValueError
  3. The ValueError is caught within the some_func() except , prints "Some other error happened" and reraises it.
  4. Back in main, I thought the reraised ValueError should get caught by the except , should print 'In main except', reraise, and then the exception itself should be uncaught causing the program to halt. But I get no exception raised and wind up in the else clause instead.

This is intended behavior and described in the documentation :

If finally is present, it specifies a 'cleanup' handler. (...) If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. (...) If the finally clause executes a return , break or continue statement, the saved exception is discarded

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM