I am trying to understand the with statement. I understand that it is supposed to replace the try/except block.
Now suppose I do something like this:
try:
name = "rubicon" / 2 # to raise an exception
except Exception as e:
print("No, not possible.")
finally:
print("OK, I caught you.")
How do I replace this with a context manager?
withdoesn’t really replacetry/except, but, rather,try/finally. Still, you can make a context manager do something different in exception cases from non-exception ones:The
return Truepart is where the context manager decides to suppress the exception (as you do by not re-raising it in yourexceptclause).