Exceptions & Files · Question 6 · Easy

The try block below completes without any error and the statement has an else clause. What is printed?

try:
    n = int("42")
except ValueError:
    print("bad")
else:
    print("ok", n)
  1. ok 42
  2. bad
  3. ok 42 bad
  4. 42
Answer and explanation

Answer: A. ok 42

Explanation: int("42") succeeds, so the except block is skipped. The else block of a try statement runs exactly when the try block raised no exception.

Previous: A file report.txt already has some text in it. What happens to that text when… · Next: io.StringIO lets a string be read like a text file. How many lines does…

Practise exceptions & files

Try a fresh set of exceptions & files questions with an explanation after every answer, free and without signing up: Exceptions & Files practice. Or sit a full placement mock test.

More exceptions & files questions

More python practice

Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops · Functions & Scope · Comprehensions & Generators

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge