Exceptions Questions with Answers

38 practice questions on Exceptions (Python) with answers and step-by-step solutions. Try 10 samples below, then practise all 38 free in the AptiNest app.

Sample questions

Question 1Easy

What is the output?

try:
    import not_a_real_module_xyz
except ImportError as e:
    print(type(e).__name__)
  1. FileNotFoundError
  2. NameError
  3. ModuleNotFoundError
  4. ImportError

Answer: C. ModuleNotFoundError

Explanation

Importing a missing module raises ModuleNotFoundError, a subclass of ImportError, so the handler catches it and prints the specific class name.

Step-by-step solution

  1. The module not_a_real_module_xyz does not exist.
  2. Python raises ModuleNotFoundError for a missing module.
  3. ModuleNotFoundError is a subclass of ImportError, so the except clause catches it.
  4. The output is ModuleNotFoundError, which is option C.

Why the other options are wrong

  • A. FileNotFoundError is for missing files, not modules.
  • B. The missing module raises an import error, not a NameError.
  • D. The exact class printed is ModuleNotFoundError, not the broader ImportError.

Tip: Use the exact class name with type(e).__name__; ModuleNotFoundError is a kind of ImportError.

Question 2Easy

What happens when this code runs?

d = {}
print(d["k"])
  1. A KeyError is raised
  2. An IndexError is raised
  3. It prints None
  4. It prints an empty string

Answer: A. A KeyError is raised

Explanation

Indexing a dict with a missing key raises KeyError. Use d.get('k') to get None instead.

Step-by-step solution

  1. d is an empty dict.
  2. d['k'] looks up a missing key.
  3. Square-bracket access on a missing key raises KeyError.

Why the other options are wrong

  • B. IndexError is for sequences like lists.
  • C. Only d.get('k') would give None.
  • D. Nothing prints an empty string.

Tip: Use d.get(k) or 'k in d' to avoid KeyError.

Question 3Easy

What is the output?

try:
    n = 5 / 0
except ZeroDivisionError:
    n = -1
print(n)
  1. ZeroDivisionError
  2. inf
  3. 0
  4. -1

Answer: D. -1

Explanation

Dividing by zero raises ZeroDivisionError, which is caught, and n is set to -1 in the handler.

Step-by-step solution

  1. 5 / 0 raises ZeroDivisionError.
  2. The except ZeroDivisionError branch runs and sets n = -1.
  3. print(n) shows -1, which is option D.

Why the other options are wrong

  • A. The error is caught, so it is not printed.
  • B. Python does not return inf for division by zero; it raises an error.
  • C. The handler sets n to -1, not 0.

Tip: Division by zero in Python raises ZeroDivisionError; it does not give inf.

Question 4Easy

Which exception does int("abc") raise?

  1. SyntaxError
  2. ValueError
  3. TypeError
  4. NameError

Answer: B. ValueError

Explanation

The argument has the right type (str) but a value that cannot be parsed as an integer, so Python raises ValueError.

Step-by-step solution

  1. int() is given a string, which is the right type.
  2. The text abc cannot be read as a whole number, so the value is wrong.
  3. That raises ValueError, the correct answer.

Why the other options are wrong

  • A. SyntaxError is wrong; the code is valid, and the error happens while it runs.
  • C. TypeError is wrong; the type is right, only the value is bad.
  • D. NameError is wrong; int is a known built-in name.

Tip: TypeError means the wrong type was given. ValueError means the right type with a bad value.

Question 5Medium

What is the output?

def f():
    try:
        return 1
    finally:
        print("F", end=" ")

print(f())
  1. 1
  2. F 1
  3. 1 F
  4. F

Answer: B. F 1

Explanation

The finally block runs before the function actually returns, so 'F ' is printed first, then print shows the returned value 1.

Step-by-step solution

  1. The function reaches return 1, so it will return 1, but the finally block runs first.
  2. Finally prints F with a space after it, and then the function returns 1.
  3. print(f()) then shows the returned 1 after F, giving F 1, the correct answer.

Why the other options are wrong

  • A. 1 is wrong; the finally block still prints F before the function ends.
  • C. 1 F is wrong; F is printed before print shows the returned value.
  • D. F is wrong; the outer print also shows the returned 1.

Tip: Finally runs even after a return, and the returned value is still sent back to the caller.

Question 6Medium

What is the output?

try:
    try:
        1 / 0
    except ZeroDivisionError as e:
        raise ValueError("bad") from e
except ValueError as v:
    print(type(v.__cause__).__name__)
  1. None
  2. NoneType
  3. ZeroDivisionError
  4. ValueError

Answer: C. ZeroDivisionError

Explanation

raise ... from e sets the new exception's __cause__ to e, which here is the ZeroDivisionError.

Step-by-step solution

  1. The ZeroDivisionError is raised by 1 / 0 and caught as e.
  2. raise ValueError from e sets the new exception's __cause__ to e.
  3. So v.__cause__ is the ZeroDivisionError object.
  4. Its type name is ZeroDivisionError.

Why the other options are wrong

  • A. The cause is set by raise ... from, so it is not None.
  • B. The cause is an exception, not NoneType.
  • D. The cause is the original ZeroDivisionError, not the ValueError.

Tip: raise NewError from err stores the original error in __cause__.

Question 7Medium

What is the output?

class AppError(Exception):
    pass

class DbError(AppError):
    pass

try:
    raise DbError("x")
except AppError:
    print("app")
except DbError:
    print("db")
  1. db
  2. app
  3. DbError traceback
  4. app db

Answer: B. app

Explanation

except clauses are tested in order and DbError is a subclass of AppError, so the first clause matches; the more specific clause never runs.

Step-by-step solution

  1. DbError is raised and is a subclass of AppError.
  2. Except clauses are tried in order, so the AppError clause is checked first.
  3. That clause matches the subclass, so app is printed.
  4. The output is app.

Why the other options are wrong

  • A. The first matching clause wins, and AppError is checked first.
  • C. The exception is caught by a handler, so no traceback is printed.
  • D. Only one clause runs, so app db is never printed.

Tip: Put more specific except clauses before more general ones.

Question 8Medium

What is the output?

def f():
    try:
        return "try"
    finally:
        return "finally"

print(f())
  1. finally
  2. SyntaxError
  3. try finally
  4. try

Answer: A. finally

Explanation

A return in finally overrides the pending return from try, so the function returns "finally". (Python 3.12 still allows it; linters warn about it.)

Step-by-step solution

  1. The try block returns try, but the finally block runs before the function exits.
  2. The finally block returns finally, which replaces the pending return value.
  3. So the function returns finally.
  4. The output is finally.

Why the other options are wrong

  • B. The code is valid Python, so no SyntaxError is raised.
  • C. Only one value is returned, so try finally is not produced.
  • D. The return in finally overrides the return in try, so try is not printed.

Tip: A return inside finally overrides any return from try; avoid it because it hides exceptions.

Question 9Hard

What is the output?

try:
    try:
        raise KeyError("k")
    finally:
        print("F", end=" ")
except KeyError as e:
    print(repr(e))
  1. F KeyError: k
  2. F 'k'
  3. F KeyError('k')
  4. KeyError('k')

Answer: C. F KeyError('k')

Explanation

finally runs while the exception propagates, printing F; the outer handler then prints repr(e), which is KeyError('k').

Step-by-step solution

  1. The inner finally block runs while the KeyError is propagating, so F is printed first.
  2. The outer except catches the KeyError as e.
  3. repr(e) gives KeyError('k').
  4. The output is F KeyError('k').

Why the other options are wrong

  • A. The printed text uses repr, not the message format, so KeyError: k is not shown.
  • B. Repr of a KeyError shows KeyError('k'), not just 'k'.
  • D. F is printed first, because finally runs before the outer handler.

Tip: A finally block runs even when an exception passes through it; repr shows the exception type and arguments.

Question 10Hard

What is the output?

import sys
try:
    sys.exit(3)
except Exception:
    print("caught Exception")
except BaseException as e:
    print("base", type(e).__name__, e.code)
  1. base SystemExit 3
  2. base SystemExit None
  3. caught Exception
  4. Nothing is printed; the program exits with code 3

Answer: A. base SystemExit 3

Explanation

sys.exit raises SystemExit, which inherits from BaseException but not Exception, so only the second handler catches it; code holds 3.

Step-by-step solution

  1. sys.exit(3) raises SystemExit, which is not a subclass of Exception.
  2. The first except Exception does not match it.
  3. The second except BaseException matches it, and the code value is 3.
  4. The output is base SystemExit 3.

Why the other options are wrong

  • B. sys.exit(3) stores 3 in code, so the value is not None.
  • C. SystemExit does not inherit from Exception, so that clause does not run.
  • D. The BaseException clause catches the exit, so the program does not just exit.

Tip: SystemExit inherits from BaseException, so a plain except Exception does not catch it.

Practise all 38 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all Python topics · All topics