31.03.20 01:32, Christopher Barker пише:
> In case Serhiy's answer wasn't clear: context managers can be written to
> handle exceptions (within their context) in any way you see fit.
>
> that is: the method:
> |
> |
> |__exit__(||self||, exc_type, exc_value, exc_traceback):|
>
> get the exception, and information about it, of one is raised, so you
> can handle it anyway you want.
Actually I meant the opposite.
I think I was thrown by the use of the example "my_context" -- that is, if you are writing a conrtect manger, you can handle exceptions any way you like. If you are using an existing one, then, yes:
the context manager does not silence a raised exception, so control flow
is never passed to the statement past the with block if an exception is
raised inside the with block.
was_not_raised = False
with my_context():
do_something_sensitive()
was_not_raised = True
if was_not_raised:
print("We're all safe.")
You do not need a special syntax for this.
but we don't need special syntax for "else" on a for or while loop (or try block) either, you could always set a sentinel for those too.
which to me is a case for adding else to a "with" block as well, for all the same reasons it's there for the other block construct.
Though I don't think I'd advocate it in this case, as the Exception is not really a clear part of the context manger API, like "break" is to the loops.