Objective
Create a Python program that shows that a context manager is always closed, even when an error occurs inside the block, and that several resources are closed in the reverse order of opening.
Instructions
- Create the class
Resourcewith__enter__(which showsOpen nameand returns the object) and__exit__(which showsClose nameand returnsFalse, without hiding the error). - Read two names and a third line that is
1if the program must fail or0if not. - With a single
withopen the two resources (with Resource(a) as r1, Resource(b) as r2). Inside, showUsing a and b; if it must fail, raiseRuntimeErrorwith the messageprocessing failed; otherwise showProcess finished. - Catch the error outside the
withblock and showError: message.
bd
red
1
Open bd
Open red
Using bd and red
Close red
Close bd
Error: processing failed
Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.
Start exercise