No, because finally
is executed always, not just when an exception has been raised and handled. It'll be executed when there is no exception, or an exception was raised you do not handle, or you used return
or used continue
or break
in a loop outside the try
, etc.
If an exception has been handled, then names you bind in an except
suite will remain set by the time the finally
suite executes, but you need to set them to sentinel values first lest you want to avoid NameError
or UnboundLocal
exceptions in case no such exception was raised:
subject = message = None
try:
some_function()
except exceptions.ExceptionA as e:
self.logger.error("Error")
subject = 'error A'
message = 'Check error A'
except exceptions.ExceptionB as b:
self.logger.error("Error")
subject = 'error A'
message = 'Check error A'
finally:
# message and subject *can* be bound to None now
self.publish(subject, message)
sys.exit()
If you wanted to execute code only if an exception was raised and handled, you'll have to do so explicitly for each except
suite. You cannot use finally
for that case, not without additional checking (you could gate on subject is not None
for example).