Editor

Python exception handling MCQ questions with answers

try, except, else and finally: which block runs, and in what order.

0 of 20 answered

  1. Question 1 · Easy

    What is the output of this code?

    try:
        print("start")
        x = 10 / 0
        print("after")
    except ZeroDivisionError:
        print("caught")
    print("end")
    Show the answer

    Answer: C

    The try block runs until the error: "start" prints, then 10 / 0 raises ZeroDivisionError and the rest of the block, including "after", is skipped. The matching except prints "caught", and the program carries on to print "end".

    Run this code in the editor
  2. Question 2 · Easy

    What is the output of this code?

    try:
        n = int("42")
    except ValueError:
        print("bad")
    else:
        print("good", n)
    finally:
        print("done")
    Show the answer

    Answer: A

    int("42") succeeds, so the except block is skipped and the else block runs. The finally block runs last, whether or not an error happened.

    Run this code in the editor
  3. Question 3 · Medium

    What is the output of this code?

    try:
        items = [1, 2, 3]
        print(items[5])
    except LookupError:
        print("lookup")
    except IndexError:
        print("index")
    Show the answer

    Answer: D

    Python checks the except clauses from top to bottom and runs only the first one that matches. IndexError is a subclass of LookupError, so the first clause catches it and the IndexError clause never runs. Put the more specific exception first.

    Run this code in the editor
  4. Question 4 · Medium

    What is the output of this code?

    def check(n):
        try:
            return n * 2
        finally:
            print("finally runs")
    
    print(check(5))
    Show the answer

    Answer: B

    When the try block reaches return, Python works out the value 10 and then runs finally before the function actually returns. So "finally runs" is printed during the call, and the outer print shows 10 afterwards.

    Run this code in the editor
  5. Question 5 · Hard

    What is the output of this code?

    def result():
        try:
            return "try"
        finally:
            return "finally"
    
    print(result())
    Show the answer

    Answer: B

    finally runs after the try block's return value is computed, and a return inside finally replaces that value, so the function returns "finally". Because it silently discards the first result (and would also discard an exception), avoid return in finally; newer Python versions warn about it.

    Run this code in the editor
  6. Question 6 · Medium

    What is the output of this code?

    for value in ["5", "x", "0"]:
        try:
            result = 10 / int(value)
        except ValueError:
            print("not a number")
        except ZeroDivisionError:
            print("zero")
        else:
            print(result)
    Show the answer

    Answer: D

    "5" gives 10 / 5 = 2.0 (/ always returns a float), which else prints. int("x") raises ValueError; int("0") works but dividing by 0 raises ZeroDivisionError. Each value reaches a different block, and the loop goes on after each one.

    Run this code in the editor
  7. Question 7 · Easy

    What is the output of this code?

    try:
        raise ValueError("age must be positive")
    except ValueError as e:
        print("Error:", e)
    Show the answer

    Answer: A

    raise creates the exception with a message, and as e names the exception object. Printing an exception shows only its message, without the class name; the form ValueError('age must be positive') is what repr(e) gives.

    Run this code in the editor
  8. Question 8 · Medium

    What is the output of this code?

    class LowBalance(Exception):
        pass
    
    def withdraw(balance, amount):
        if amount > balance:
            raise LowBalance(f"need {amount - balance} more")
        return balance - amount
    
    try:
        print(withdraw(100, 30))
        print(withdraw(100, 150))
    except LowBalance as e:
        print("Failed:", e)
    Show the answer

    Answer: C

    The first call returns 70, which prints. The second call raises the custom exception before it can return, so its print never runs and the except clause prints the message. A custom exception is a class that inherits from Exception.

    Run this code in the editor
  9. Question 9 · Hard

    What is the output of this code?

    stock = {"pen": 10}
    try:
        print(stock["pencil"])
    except KeyError as e:
        print("Missing:", e)
    Show the answer

    Answer: D

    A KeyError carries the missing key, and printing a KeyError shows the key's repr, quotes included. Most other exceptions print their message as plain text, which is why "Missing: pencil" is the tempting answer.

    Run this code in the editor
  10. Question 10 · Medium

    What is the output of this code?

    try:
        try:
            int("abc")
        except ValueError:
            print("inner")
            raise
        finally:
            print("inner finally")
    except ValueError:
        print("outer")
    Show the answer

    Answer: C

    The inner except prints "inner", then a bare raise sends the same ValueError on. Before it leaves the inner try statement, that statement's finally prints "inner finally". Only then does the outer except catch the error and print "outer".

    Run this code in the editor
  11. Question 11 · Easy

    What is the output of this code?

    total = 0
    for item in [4, "a", 6]:
        try:
            total += item
        except TypeError:
            print("skipped", item)
    print(total)
    Show the answer

    Answer: B

    Adding the string "a" to an int raises TypeError, which the except block catches and reports. The loop then carries on with 6, so the total is 4 + 6 = 10.

    Run this code in the editor
  12. Question 12 · Hard

    What is the output of this code?

    count = 0
    for i in range(3):
        try:
            if i == 1:
                continue
            count += 10
        finally:
            count += 1
    print(count)
    Show the answer

    Answer: A

    finally runs every time the try block is left, including when continue jumps to the next turn of the loop. All three turns add 1, and only i = 0 and i = 2 add 10: 10 + 1 + 1 + 10 + 1 = 23. The tempting 22 forgets the finally on the skipped turn.

    Run this code in the editor
  13. Question 13 · Easy

    Which error does this code raise?

    marks = [90, 85, 77]
    print(marks[3])
    print(int("A"))
    Show the answer

    Answer: A, IndexError: list index out of range

    The indexes of a 3-item list run from 0 to 2, so marks[3] raises IndexError. The program stops at the first unhandled error, so the line with int("A"), which would raise ValueError, never runs.

    Run this code in the editor
  14. Question 14 · Medium

    Which error does this code raise?

    def set_age(age):
        if age < 0:
            raise "Age cannot be negative"
        return age
    
    set_age(-1)
    Show the answer

    Answer: B, TypeError: exceptions must derive from BaseException

    raise needs an exception class or object, such as ValueError("Age cannot be negative"). A plain string is not an exception, so the raise line itself fails with TypeError. The code is valid syntax, so it is not a SyntaxError.

    Run this code in the editor
  15. Question 15 · Hard

    What happens when this code runs?

    try:
        result = 10 / 0
    except ZeroDivisionError as err:
        message = "division failed"
    print(message)
    print(err)
    Show the answer

    Answer: C, NameError: name 'err' is not defined

    The name after as is deleted when the except block ends. message survives, so "division failed" prints, but print(err) then raises NameError. Copy it inside the block, as in saved = err, if you need it later.

    Run this code in the editor
  16. Question 16 · Easy

    In a try statement, when does the else block run?

    Show the answer

    Answer: D, Only when the try block raised no exception

    else holds code that should run only if the try block finished without an exception. It runs before finally, and it is skipped whenever an exception occurs, whether or not an except block catches it.

  17. Question 17 · Medium

    Which class should a custom exception class normally inherit from?

    Show the answer

    Answer: C, Exception

    Exception is the base of all ordinary errors, so except Exception also catches your class. BaseException is the root, but it also covers KeyboardInterrupt and SystemExit, which programs should not normally catch. Python has no built-in class named Error, and a plain object cannot be raised.

  18. Question 18 · Easy

    In what order must the clauses of a complete try statement be written?

    Show the answer

    Answer: D, try, except, else, finally

    The try block comes first, then one or more except clauses, then an optional else, with finally always last. Any other order is a SyntaxError. A try with only a finally clause is also valid.

  19. Question 19 · Easy

    Which code prints invalid when text cannot be turned into an int, and prints the number otherwise?

    Show the answer

    Answer: A

    int("abc") raises ValueError, so that is the exception to catch. Catching TypeError lets the ValueError through, finally prints "invalid" every time, and the if version crashes on bad text before it can choose a branch (and calls "0" invalid).

  20. Question 20 · Medium

    Which class makes print(e) show Too cold: -5 after raise TooCold(-5) is caught with except TooCold as e?

    Show the answer

    Answer: B

    print(e) uses str(e), so overriding __str__ controls the message. Overriding only __repr__ leaves str(e) as "-5", built from the arguments. A class that does not inherit from Exception cannot be raised at all, and a class attribute changes nothing about the printed text.

Keep going