Exception handling in Python provides a structured mechanism to catch, handle, and manage runtime errors without abruptly crashing an application. Python utilizes blocks defined by keywords try, except, else, and finally to separate critical logic from fault-tolerant recovery code. All built-in exceptions inherit from BaseException, with standard application-level errors deriving from the Exception root class. Modern Python versions (Python 3.11+) also support concurrency-aware constructs like ExceptionGroup and except* to manage multiple simultaneous errors cleanly. Master key error handling principles, built-in exception hierarchies, exception chaining using raise ... from, and context management to build resilient, production-grade applications and prepare for technical software engineering assessments.
Python Exception / Error Handling MCQs
1 min read
Correct Answer: b) ImportError
Explanation:
ImportError is raised when an import statement fails to find the requested attribute or name within a module, whereas ModuleNotFoundError is specifically for when the module file itself cannot be located.
Correct Answer: b) To encapsulate multiple unrelated exceptions raised concurrently
Explanation:
Python 3.11 introduced BaseExceptionGroup and ExceptionGroup to wrap multiple exceptions together, typically useful in asynchronous programming with task groups.
Correct Answer: b) It is added to a new ExceptionGroup and propagated upward
Explanation:
In Python 3.11+, unhandled exceptions inside an except* block are collected into a new ExceptionGroup along with any remaining unhandled exceptions and raised.
Correct Answer: c) contextlib
Explanation:
contextlib.suppress(*exceptions) is a context manager used to cleanly ignore specified exceptions within a with-statement block.
Correct Answer: b) It raises a RuntimeError stating no active exception to re-raise
Explanation:
Using a bare 'raise' outside of an active exception handling context results in a RuntimeError because there is no active exception to re-raise.
Correct Answer: a) It intercepts exceptions that occur where they cannot be handled, such as in __del__ methods
Explanation:
sys.unraisablehook allows customizing how unraisable exceptions (like exceptions raised during garbage collection in __del__) are handled.
Correct Answer: b) threading.excepthook is invoked, and the thread terminates while the main process continues
Explanation:
Exceptions in worker threads do not automatically crash the main thread; instead, threading.excepthook handles the uncaught thread exception.
Correct Answer: b) OSError
Explanation:
System and resource limit errors (like reaching file descriptor limits) typically manifest as specific subclasses of OSError.
Correct Answer: b) __cause__
Explanation:
When raising an exception with 'raise new_exc from orig_exc', orig_exc is stored in the '__cause__' attribute.
Correct Answer: b) True
Explanation:
Using 'from None' sets '__suppress_context__' to True, which tells the exception formatter not to print the context exception.
Correct Answer: a) struct.error
Explanation:
The struct module defines its own exception class 'struct.error' for packing/unpacking failures.
Correct Answer: b) json.decoder.JSONDecodeError
Explanation:
json.loads() raises JSONDecodeError (which inherits from ValueError) when decoding invalid JSON text.
Correct Answer: b) JSONDecodeError inherits from ValueError
Explanation:
json.decoder.JSONDecodeError is a subclass of ValueError.
Correct Answer: b) SyntaxError
Explanation:
Using assignment operator '=' instead of comparison '==' inside an if-condition is invalid Python syntax and produces a SyntaxError during parsing.
Correct Answer: a) pickle.UnpicklingError
Explanation:
The pickle module raises pickle.UnpicklingError when unpickling an object fails due to invalid or corrupted data.
Correct Answer: a) ZeroDivisionError
Explanation:
Dividing any numeric type (int, float, Decimal) by zero raises ZeroDivisionError in standard Python configurations.
Correct Answer: b) When floating-point IEEE 754 exceptions are enabled in control flags and an invalid operation occurs
Explanation:
FloatingPointError is rarely raised unless the C layer has turned on floating-point exception traps, which standard Python builds leave off by default.
Correct Answer: b) TypeError
Explanation:
Iterating over a non-iterable object (e.g., for x in 100:) raises 'TypeError: 'int' object is not iterable'.
Correct Answer: b) ValueError
Explanation:
Passing an invalid mode string to open() raises 'ValueError: invalid mode: ...'.
Correct Answer: b) KeyError propagates out of the loop
Explanation:
Python standard sequence iteration fallback expects IndexError to signal end of sequence when relying on __getitem__. KeyError will propagate out.
Correct Answer: b) SystemExit
Explanation:
sys.exit() raises the SystemExit exception with the provided message/code passed to constructor.
Correct Answer: a) e.code == 5
Explanation:
SystemExit instances store the exit status code in the 'code' attribute.
Correct Answer: b) Only the background thread terminates
Explanation:
Raising SystemExit inside a non-main thread exits that specific thread, not the whole Python interpreter process.
Correct Answer: b) urllib.error
Explanation:
URLError is defined in the standard library module 'urllib.error'.
Correct Answer: b) urllib.error.URLError
Explanation:
HTTPError is a subclass of URLError, which in turn is a subclass of OSError.
Correct Answer: a) socket.timeout
Explanation:
socket.timeout (which is an alias for TimeoutError in modern Python) is raised when a socket operation times out.
Correct Answer: a) ConnectionRefusedError
Explanation:
ConnectionRefusedError (subclass of OSError) corresponds to ECONNREFUSED when a connection attempt is rejected by the peer.
Correct Answer: b) BrokenPipeError
Explanation:
BrokenPipeError (subclass of ConnectionError) is raised when trying to write on a pipe while the other end has been closed.
Correct Answer: b) ConnectionError
Explanation:
ConnectionError is the abstract base class for connection-related OSError subclasses.
Correct Answer: b) ValueError
Explanation:
math.sqrt(-1) raises 'ValueError: math domain error' because domain of real square root does not include negative numbers.
Correct Answer: b) No error, returns 1j
Explanation:
The cmath module operates on complex numbers, so cmath.sqrt(-1) safely evaluates to 1j without raising an exception.
Correct Answer: b) SyntaxError
Explanation:
ast.parse() raises SyntaxError when the provided code string violates Python syntax rules.
Correct Answer: a) The line number in the source file where error was detected
Explanation:
SyntaxError objects hold details about the parsing failure, including 'lineno', 'offset', 'text', and 'filename'.
Correct Answer: b) ValueError
Explanation:
compile() raises ValueError if the source string contains null bytes.
Correct Answer: b) RecursionError
Explanation:
Deeply nested code structures evaluated via eval() will raise RecursionError when stack depth limits are reached.
Correct Answer: a) TypeError
Explanation:
sys.getrefcount expects a valid Python object reference; invalid types trigger a TypeError.
Correct Answer: b) ReferenceError
Explanation:
ReferenceError is raised when a weak reference proxy object is accessed after the underlying garbage collected object is dead.
Correct Answer: a) sys.excepthook
Explanation:
sys.excepthook(type, value, traceback) is called whenever an uncaught exception occurs.
Correct Answer: b) The secondary exception is printed to stderr and program exits
Explanation:
If sys.excepthook raises an exception, Python prints a message about the excepthook failure along with the original error to stderr.
Correct Answer: b) traceback
Explanation:
traceback.format_exc() formats the stack trace of the currently handled exception into a single string.
Correct Answer: b) A list of strings formatted as stack trace lines
Explanation:
traceback.format_exception returns a list of formatted strings, each ending with a newline.
Correct Answer: d) Command-line flags cannot disable tracebacks; sys.excepthook must be modified
Explanation:
Disabling or suppressing tracebacks programmatically requires overriding sys.excepthook or handling exceptions manually.
Correct Answer: b) DeprecationWarning
Explanation:
DeprecationWarning is targeted at developers to warn about features that are deprecated.
Correct Answer: b) FutureWarning
Explanation:
FutureWarning is intended to alert end users of applications about upcoming behavioral changes.
Correct Answer: a) python -W error script.py
Explanation:
Passing '-W error' treats all warnings as exceptions, causing them to raise rather than log.
Correct Answer: a) warnings.catch_warnings()
Explanation:
warnings.catch_warnings() temporarily redirects warnings and allows local filter modifications within a with-block.
Correct Answer: a) Ignores all warnings globally across the process
Explanation:
warnings.simplefilter('ignore') sets the filter action to drop all subsequent warnings matching default criteria.
Correct Answer: a) Matching exceptions are split off from the group and handled, while remaining exceptions propagate
Explanation:
Python 3.11 except* allows matching specific exception types inside an ExceptionGroup, splitting matching errors while non-matching ones re-raise.
Correct Answer: b) No, if the group contains BaseException derivatives, BaseExceptionGroup is used and ignored by 'except Exception'
Explanation:
A BaseExceptionGroup containing KeyboardInterrupt or SystemExit does not inherit from Exception, so 'except Exception' will not catch it.
Correct Answer: a) The first exception encountered propagates immediately out of gather()
Explanation:
By default in asyncio.gather, if any task raises an exception, that exception is immediately raised to the caller.
Correct Answer: a) It cancels remaining tasks in the group and raises an ExceptionGroup containing all failures
Explanation:
asyncio.TaskGroup cancels remaining tasks upon failure and raises an ExceptionGroup to aggregate errors.
Correct Answer: a) asyncio.CancelledError
Explanation:
Calling result() on a Task that has been cancelled raises asyncio.CancelledError (which inherits from BaseException in Python 3.8+).
Correct Answer: b) BaseException
Explanation:
In Python 3.8+, CancelledError inherits directly from BaseException so that accidental 'except Exception:' blocks do not catch it.
Correct Answer: b) TimeoutError
Explanation:
In Python 3.11+, asyncio.TimeoutError is an alias for the built-in TimeoutError exception.
Correct Answer: b) AttributeError
Explanation:
Attempting attribute access or method invocation on None raises 'AttributeError: 'NoneType' object has no attribute ...'.
Correct Answer: b) ValueError
Explanation:
Mismatch in unpacking count produces 'ValueError: not enough values to unpack (expected 3, got 2)'.
Correct Answer: a) ValueError
Explanation:
Unpacking too many values produces 'ValueError: too many values to unpack (expected 2)'.
Correct Answer: b) ValueError
Explanation:
int('3.14') raises 'ValueError: invalid literal for int() with base 10: '3.14''.
Correct Answer: b) TypeError
Explanation:
Invoking a non-callable object raises 'TypeError: 'int' object is not callable'.
Correct Answer: a) TypeError
Explanation:
Bitwise operations require integer operands; passing floats raises 'TypeError: unsupported operand type(s) for &'.
Correct Answer: a) FileExistsError
Explanation:
FileExistsError (subclass of OSError) is raised when creating a file or directory that already exists.
Correct Answer: b) OSError
Explanation:
Removing a non-empty directory with os.rmdir raises an OSError (specifically ENOTEMPTY / Directory not empty).
Correct Answer: b) The exception propagates immediately out of any()
Explanation:
Exceptions raised during generator evaluation inside built-in functions like any() or all() propagate immediately.
Correct Answer: c) logging
Explanation:
logging.exception(msg) logs a message with level ERROR and automatically appends exception traceback information.
Correct Answer: a) Inside an except block
Explanation:
logging.exception() inspects current active exception via sys.exc_info(), so it must be called inside an except handler.
Correct Answer: b) AttributeError
Explanation:
Deleting a non-existent attribute on any object via delattr() raises AttributeError.
Correct Answer: b) LookupError
Explanation:
Passing an invalid codec name (e.g., 'hello'.encode('foo')) raises 'LookupError: unknown encoding: foo'.
Correct Answer: a) KeyError inherits from LookupError
Explanation:
KeyError and IndexError both subclass LookupError.
Correct Answer: c) ValueError
Explanation:
list.index(x) raises 'ValueError: x is not in list'.
Correct Answer: b) KeyError
Explanation:
popping a non-existent key from dict without specifying a default argument raises KeyError.
Correct Answer: b) Returns None without raising an exception
Explanation:
Providing a default parameter to dict.pop() prevents KeyError and returns the default value instead.
Correct Answer: a) PermissionError
Explanation:
PermissionError is raised when system permission settings prevent performing requested file/device operation.
Correct Answer: b) io.UnsupportedOperation
Explanation:
io.UnsupportedOperation (subclass of ValueError and OSError) is raised when performing unsupported stream operations like writing to read-only handle.
Correct Answer: a) StopIteration
Explanation:
StopIteration is raised by iterators to signal that there are no remaining elements.
Correct Answer: b) It is converted into a RuntimeError
Explanation:
PEP 479 (default in 3.7+) transforms explicitly raised StopIteration exceptions inside generators into RuntimeError to prevent accidental iteration swallowing.
Correct Answer: b) Exceptions in __del__ are ignored and written to sys.unraisablehook / stderr
Explanation:
Because destructors run during garbage collection, exceptions raised inside __del__ cannot be handled normally; Python writes warning to stderr or sys.unraisablehook.
Correct Answer: b) SyntaxError
Explanation:
exec() compiles and executes Python code strings at runtime and raises SyntaxError if syntax parsing fails.
Correct Answer: b) OverflowError
Explanation:
int.to_bytes() raises OverflowError if integer is too large to fit in specified byte length.
Correct Answer: b) TypeError
Explanation:
Sequence repetition requires an integer count; passing float raises 'TypeError: can't multiply sequence by non-int of type 'float''.
Correct Answer: b) IndexError
Explanation:
Positional formatting missing required arguments raises 'IndexError: Replacement index 1 out of range for positional args tuple'.
Correct Answer: a) KeyError
Explanation:
Keyword string formatting missing arguments raises KeyError for missing key.
Correct Answer: b) TypeError
Explanation:
Metaclass conflicts during class creation raise 'TypeError: metaclass conflict: the metaclass of a derived class must be a (strict) subclass of the metaclasses of all its bases'.
Correct Answer: d) Segmentation Fault / Access Violation (often fatal or raises OSError depending on OS)
Explanation:
Ctypes level invalid memory access typically results in OS low level signals or hardware fault exceptions.
Correct Answer: c) OSError
Explanation:
Subclasses of OSError are raised when OS-level file or directory creation in temp directory fails.
Correct Answer: b) TypeError
Explanation:
Sets are unindexed collections; attempting index slicing raises 'TypeError: 'set' object is not subscriptable'.
Correct Answer: b) TypeError
Explanation:
Adding unhashable objects to set raises 'TypeError: unhashable type: 'list''.
Correct Answer: b) TypeError
Explanation:
Dictionary keys must be hashable; mutable objects like lists or dicts raise 'TypeError: unhashable type'.
Correct Answer: b) TypeError
Explanation:
Tuples are immutable; item assignment raises 'TypeError: 'tuple' object does not support item assignment'.
Correct Answer: a) AttributeError
Explanation:
Tuples do not have an append method; attempting to call non-existent method raises AttributeError.
Correct Answer: b) ValueError
Explanation:
Hexadecimal bytes conversion requires pairs of digits; odd-length strings raise 'ValueError: non-hexadecimal number found / odd-length string'.
Correct Answer: b) ValueError
Explanation:
Factorial is defined for non-negative integers; negative inputs raise 'ValueError: factorial() not defined for negative values'.
Correct Answer: a) ValueError
Explanation:
In modern Python math module, math.factorial(5.5) raises ValueError (factorial() only accepts integral values).
Correct Answer: b) ValueError
Explanation:
Signal handling in Python must occur in the main thread; calling signal.signal() from subthread raises 'ValueError: signal only works in main thread'.
Correct Answer: a) ProcessLookupError
Explanation:
ProcessLookupError (subclass of OSError) is raised when given process ID does not exist.
Correct Answer: b) IndexError
Explanation:
Popping from an empty collections.deque raises 'IndexError: pop from an empty deque'.
Correct Answer: b) queue.Empty
Explanation:
Non-blocking fetch on empty Queue raises the queue module's exception 'queue.Empty'.
Correct Answer: b) queue.Full
Explanation:
Non-blocking put on full Queue raises the queue module's exception 'queue.Full'.
Correct Answer: a) UnicodeEncodeError
Explanation:
UnicodeEncodeError is raised when converting unicode characters into byte encodings that do not support those characters.
Correct Answer: a) UnicodeEncodeError inherits from UnicodeError
Explanation:
UnicodeEncodeError is a subclass of UnicodeError (which is a subclass of ValueError).
Correct Answer: a) ValueError
Explanation:
Setting limit below minimal threshold raises 'ValueError: limit must be > 0'.
Correct Answer: b) Catches absolutely all exceptions including SystemExit, KeyboardInterrupt, and GeneratorExit
Explanation:
BaseException is the root of exception tree. Catching it traps system signal exceptions alongside standard errors.
Correct Answer: a) It prevents exceptions from being caught by standard 'except Exception:' blocks
Explanation:
Standard error handling catches 'Exception'. Custom exceptions deriving from BaseException bypass typical error handling logic.
Correct Answer: b) Ensuring resources are safely cleaned up (e.g. via context managers or finally) even when exceptions occur
Explanation:
Exception safety refers to ensuring consistent application state and releasing system resources when errors occur.
Related Posts

Java Functions MCQs
In Java, functions are formally known as methods and serve as modular blocks of reusable code encapsulated within classes. A…
October 19, 2026By MCQs Generator
No Image
C++ Templates - MCQs
1. Which of the following built-in exceptions is raised when an imported name cannot be found in a module during…
October 19, 2026By MCQs Generator

JavaScript Loops MCQs
Iteration structures in JavaScript allow developers to execute code blocks repeatedly based on dynamic boolean conditions. Standard loops such as…
October 19, 2026By MCQs Generator
Related Categories

AI & Data Science MCQ
5 topics
By MCQs Generator

Arts & Humanities MCQ
4 topics
By MCQs Generator

Civil Engineering MCQ
4 topics
By MCQs Generator

Commerce & Business MCQ
4 topics
By MCQs Generator

Competitive Exams MCQ
5 topics
By MCQs Generator

Electrical & Electronics Engineering MCQ
3 topics
By MCQs Generator

General Knowledge MCQ
2 topics
By MCQs Generator

General Science MCQ
4 topics
By MCQs Generator

Law & Judiciary MCQ
3 topics
By MCQs Generator

Mechanical Engineering MCQ
4 topics
By MCQs Generator

Medical & Health Sciences MCQ
4 topics
By MCQs Generator

Modern Tech Fields MCQ
3 topics
By MCQs Generator