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.
some_func()
within my main programsome_func()
raises ValueError some_func()
except
, prints "Some other error happened" and reraises it. 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 thefinally
clause executes areturn
,break
orcontinue
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.