Try, Except & Finally

Preview — 3 of 10 questions

What is the output of the following code?

javascript
def check(n):
    try:
        result = 10 / n
    except ZeroDivisionError:
        print("error")
    else:
        print("no error")
    finally:
        print("cleanup")
    return result

check(2)
Acleanup then no error
Berror then cleanup
Cno error only — finally doesn't run when no exception occurs
Dno error then cleanup

What is the output of the following code?

javascript
def parse(value):
    try:
        return int(value)
    except (ValueError, TypeError) as e:
        return f"failed: {type(e).__name__}"

print(parse("abc"))
print(parse(None))
print(parse("42"))
Afailed: ValueError, failed: TypeError, 42
BNone, None, 42
Cfailed: ValueError, failed: ValueError, 42
DTypeError: catching classes that do not inherit from BaseException is not allowed

What is the output of the following code?

javascript
try:
    raise ValueError("bad value")
except Exception:
    print("caught generic")
except ValueError:
    print("caught specific")
ASyntaxError: default 'except:' must be last
BBoth are printed.
Ccaught generic
Dcaught specific

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.