Python exception handling MCQ questions with answers
try, except, else and finally: which block runs, and in what order.
0 of 20 answered
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
Run this code in the editortryblock runs until the error: "start" prints, then10 / 0raises ZeroDivisionError and the rest of the block, including "after", is skipped. The matchingexceptprints "caught", and the program carries on to print "end".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
Run this code in the editorint("42")succeeds, so theexceptblock is skipped and theelseblock runs. Thefinallyblock runs last, whether or not an error happened.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
Run this code in the editorexceptclauses 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 theIndexErrorclause never runs. Put the more specific exception first.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
Run this code in the editortryblock reachesreturn, Python works out the value 10 and then runsfinallybefore the function actually returns. So "finally runs" is printed during the call, and the outerprintshows 10 afterwards.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
Run this code in the editorfinallyruns after thetryblock's return value is computed, and areturninsidefinallyreplaces that value, so the function returns "finally". Because it silently discards the first result (and would also discard an exception), avoidreturninfinally; newer Python versions warn about it.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 (
Run this code in the editor/always returns a float), whichelseprints.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.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
Run this code in the editorraisecreates the exception with a message, andas enames the exception object. Printing an exception shows only its message, without the class name; the formValueError('age must be positive')is whatrepr(e)gives.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
Run this code in the editorprintnever runs and theexceptclause prints the message. A custom exception is a class that inherits from Exception.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
Run this code in the editorrepr, quotes included. Most other exceptions print their message as plain text, which is why "Missing: pencil" is the tempting answer.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
Run this code in the editorexceptprints "inner", then a bareraisesends the same ValueError on. Before it leaves the innertrystatement, that statement'sfinallyprints "inner finally". Only then does the outerexceptcatch the error and print "outer".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
Run this code in the editorexceptblock catches and reports. The loop then carries on with 6, so the total is 4 + 6 = 10.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
Run this code in the editorfinallyruns every time thetryblock is left, including whencontinuejumps 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 thefinallyon the skipped turn.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
Run this code in the editormarks[3]raises IndexError. The program stops at the first unhandled error, so the line withint("A"), which would raise ValueError, never runs.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
Run this code in the editorraiseneeds an exception class or object, such asValueError("Age cannot be negative"). A plain string is not an exception, so theraiseline itself fails with TypeError. The code is valid syntax, so it is not a SyntaxError.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
Run this code in the editorasis deleted when theexceptblock ends.messagesurvives, so "division failed" prints, butprint(err)then raises NameError. Copy it inside the block, as insaved = err, if you need it later.Question 16 · Easy
In a
trystatement, when does theelseblock run?Show the answer
Answer: D, Only when the
tryblock raised no exceptionelseholds code that should run only if thetryblock finished without an exception. It runs beforefinally, and it is skipped whenever an exception occurs, whether or not anexceptblock catches it.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 Exceptionalso 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.Question 18 · Easy
In what order must the clauses of a complete
trystatement be written?Show the answer
Answer: D, try, except, else, finally
The
tryblock comes first, then one or moreexceptclauses, then an optionalelse, withfinallyalways last. Any other order is a SyntaxError. Atrywith only afinallyclause is also valid.Question 19 · Easy
Which code prints
invalidwhentextcannot 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,finallyprints "invalid" every time, and theifversion crashes on bad text before it can choose a branch (and calls "0" invalid).Question 20 · Medium
Which class makes
print(e)showToo cold: -5afterraise TooCold(-5)is caught withexcept TooCold as e?Show the answer
Answer: B
print(e)usesstr(e), so overriding__str__controls the message. Overriding only__repr__leavesstr(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
- Read the lesson behind these questions: Exceptions in the PythonBook
- Next topic: Python OOP MCQ questions with answers
- Before this: Python lambda, map and filter MCQ questions with answers
- Write the code yourself in the Python coding challenges, which check your solution with tests.