Error and Exception Handling · 18 / 20 Exercise Medium

The order of try, else and finally

Objective

Understanding the order in which try, except, else and finally run is key: finally always runs, even when the try has already done return.

Instructions

  • Define process(mode, log) that appends to a list each block that runs (try, except, else, finally). Depending on the mode: ok ends without error; fail raises ValueError (caught); return does return "R" inside the try; boom raises KeyError (not caught). It returns "OK", "E", "R" or, after the KeyError, returns nothing.
  • The first line has the number n of modes; each one is a line. Show the log separated by spaces, -> and the returned value (or propagated if the error propagated and the main program catches it).
Input
4
ok
fail
return
boom
Output
try else finally -> OK
try except finally -> E
try finally -> R
try finally -> propagated

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise