Python Exception / Error Handling MCQs

1 min read

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.

1. Which of the following built-in exceptions is raised when an imported name cannot be found in a module during a 'from ... import ...' statement?

a) NameError
b) ImportError
c) AttributeError
d) ModuleNotFoundError
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.

2. What is the primary function of the built-in 'BaseExceptionGroup' introduced in Python 3.11?

a) To replace all standard exception classes in legacy code
b) To encapsulate multiple unrelated exceptions raised concurrently
c) To convert warnings into fatal runtime exceptions
d) To automatically retry failed asynchronous tasks
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.

3. What will happen if an exception is raised inside an 'except*' handler in Python 3.11+?

a) It is silently ignored
b) It is added to a new ExceptionGroup and propagated upward
c) It immediately crashes the Python interpreter process
d) It causes a SyntaxError during compilation
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.

4. Which built-in module provides the 'suppress' context manager to ignore specified exceptions?

a) sys
b) os
c) contextlib
d) traceback
Correct Answer: c) contextlib
Explanation:
contextlib.suppress(*exceptions) is a context manager used to cleanly ignore specified exceptions within a with-statement block.

5. What happens when 'raise' is called with no arguments outside of an except block?

a) It raises the last uncaught exception in history
b) It raises a RuntimeError stating no active exception to re-raise
c) It raises a TypeError
d) It exits the program cleanly with return code 0
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.

6. What is the effect of setting 'sys.unraisablehook' in Python?

a) It intercepts exceptions that occur where they cannot be handled, such as in __del__ methods
b) It converts all unhandled exceptions into warnings
c) It prevents any exception from terminating the process
d) It suppresses all SyntaxError exceptions during import
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.

7. What exception is raised when an unhandled exception occurs in a thread managed by the 'threading' module?

a) ThreadError
b) threading.excepthook is invoked, and the thread terminates while the main process continues
c) SystemExit
d) MainThreadTerminationError
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.

8. Which exception is raised when an operation attempt exceeds a system or resource soft limit?

a) ResourceError
b) OSError
c) MemoryError
d) OverflowError
Correct Answer: b) OSError
Explanation:
System and resource limit errors (like reaching file descriptor limits) typically manifest as specific subclasses of OSError.

9. Which attribute on an exception instance stores the explicit cause provided by the 'from' keyword?

a) __context__
b) __cause__
c) __traceback__
d) __suppress_context__
Correct Answer: b) __cause__
Explanation:
When raising an exception with 'raise new_exc from orig_exc', orig_exc is stored in the '__cause__' attribute.

10. What is the default value of '__suppress_context__' on an exception raised with 'raise NewException from None'?

a) False
b) True
c) None
d) Undefined
Correct Answer: b) True
Explanation:
Using 'from None' sets '__suppress_context__' to True, which tells the exception formatter not to print the context exception.

11. Which exception is raised when 'struct.pack()' receives an argument that does not fit the specified layout code?

a) struct.error
b) ValueError
c) TypeError
d) PackError
Correct Answer: a) struct.error
Explanation:
The struct module defines its own exception class 'struct.error' for packing/unpacking failures.

12. Which built-in exception is raised when attempting to decode invalid JSON with 'json.loads()'?

a) ValueError
b) json.decoder.JSONDecodeError
c) SyntaxError
d) TypeError
Correct Answer: b) json.decoder.JSONDecodeError
Explanation:
json.loads() raises JSONDecodeError (which inherits from ValueError) when decoding invalid JSON text.

13. What is the hierarchy relationship between JSONDecodeError and ValueError?

a) ValueError inherits from JSONDecodeError
b) JSONDecodeError inherits from ValueError
c) They are unrelated classes under BaseException
d) JSONDecodeError inherits directly from BaseException
Correct Answer: b) JSONDecodeError inherits from ValueError
Explanation:
json.decoder.JSONDecodeError is a subclass of ValueError.

14. What type of error is raised if a programmer writes 'if x = 5:' in Python code?

a) ValueError
b) SyntaxError
c) AssignmentError
d) TypeError
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.

15. Which exception is raised when 'pickle.loads()' fails due to corrupted data?

a) pickle.UnpicklingError
b) TypeError
c) ValueError
d) MemoryError
Correct Answer: a) pickle.UnpicklingError
Explanation:
The pickle module raises pickle.UnpicklingError when unpickling an object fails due to invalid or corrupted data.

16. Which exception is raised when attempting to divide a float by 0.0?

a) ZeroDivisionError
b) FloatingPointError
c) OverflowError
d) ValueError
Correct Answer: a) ZeroDivisionError
Explanation:
Dividing any numeric type (int, float, Decimal) by zero raises ZeroDivisionError in standard Python configurations.

17. Under what circumstance does Python raise a 'FloatingPointError'?

a) Always when dividing floats by zero
b) When floating-point IEEE 754 exceptions are enabled in control flags and an invalid operation occurs
c) When rounding float values
d) When converting float to int
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.

18. Which exception is raised when trying to iterate over an object that does not implement __iter__ or __getitem__?

a) AttributeError
b) TypeError
c) StopIteration
d) ValueError
Correct Answer: b) TypeError
Explanation:
Iterating over a non-iterable object (e.g., for x in 100:) raises 'TypeError: 'int' object is not iterable'.

19. What exception is raised when an invalid flag is passed to 'open()' function, such as open('file.txt', 'z')?

a) IOError
b) ValueError
c) ModeError
d) OSError
Correct Answer: b) ValueError
Explanation:
Passing an invalid mode string to open() raises 'ValueError: invalid mode: ...'.

20. What happens if a custom class overrides '__getitem__' to raise KeyError, but it is used in a sequence context like 'for item in obj:'?

a) The loop stops cleanly as if StopIteration occurred
b) KeyError propagates out of the loop
c) IndexError is automatically raised
d) It converts to a TypeError
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.

21. Which exception is raised when calling 'sys.exit("Error message")'?

a) SystemError
b) SystemExit
c) RuntimeError
d) ExitError
Correct Answer: b) SystemExit
Explanation:
sys.exit() raises the SystemExit exception with the provided message/code passed to constructor.

22. What is the code property of SystemExit when sys.exit(5) is called?

a) e.code == 5
b) e.status == 5
c) e.args[0] == '5'
d) e.exit_code == 5
Correct Answer: a) e.code == 5
Explanation:
SystemExit instances store the exit status code in the 'code' attribute.

23. What happens if a background thread raises SystemExit in Python?

a) The entire process terminates immediately
b) Only the background thread terminates
c) The main thread catches it
d) It triggers a process crash report
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.

24. Which built-in module contains the exception 'urllib.error.URLError'?

a) requests
b) urllib.error
c) http.client
d) socket
Correct Answer: b) urllib.error
Explanation:
URLError is defined in the standard library module 'urllib.error'.

25. What exception class does 'urllib.error.HTTPError' derive from?

a) Exception
b) urllib.error.URLError
c) ConnectionError
d) IOError
Correct Answer: b) urllib.error.URLError
Explanation:
HTTPError is a subclass of URLError, which in turn is a subclass of OSError.

26. Which exception is raised when socket operations reach a network timeout?

a) socket.timeout
b) NetworkError
c) HTTPError
d) ConnectionRefusedError
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.

27. Which exception is raised when trying to connect to a server port where no process is listening?

a) ConnectionRefusedError
b) ConnectionResetError
c) ConnectionAbortedError
d) BrokenPipeError
Correct Answer: a) ConnectionRefusedError
Explanation:
ConnectionRefusedError (subclass of OSError) corresponds to ECONNREFUSED when a connection attempt is rejected by the peer.

28. Which exception is raised when writing to a socket or pipe whose reading end has closed?

a) ConnectionResetError
b) BrokenPipeError
c) EOFError
d) PipeError
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.

29. Which built-in exception class is the base class for ConnectionRefusedError, BrokenPipeError, and ConnectionResetError?

a) SocketError
b) ConnectionError
c) IOError
d) NetworkError
Correct Answer: b) ConnectionError
Explanation:
ConnectionError is the abstract base class for connection-related OSError subclasses.

30. What error is raised by math.sqrt(-1) in standard Python math module?

a) ZeroDivisionError
b) ValueError
c) ArithmeticError
d) ComplexError
Correct Answer: b) ValueError
Explanation:
math.sqrt(-1) raises 'ValueError: math domain error' because domain of real square root does not include negative numbers.

31. What error is raised by cmath.sqrt(-1)?

a) ValueError
b) No error, returns 1j
c) ComplexError
d) TypeError
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.

32. What exception is raised when parsing code with 'ast.parse()' containing invalid syntax?

a) ValueError
b) SyntaxError
c) ast.ASTError
d) TypeError
Correct Answer: b) SyntaxError
Explanation:
ast.parse() raises SyntaxError when the provided code string violates Python syntax rules.

33. What is stored in the 'lineno' attribute of a caught SyntaxError object?

a) The line number in the source file where error was detected
b) The total line count of the script
c) The column number of the error
d) The error code number
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'.

34. What exception is raised when 'compile()' receives source text containing null bytes?

a) NullByteError
b) ValueError
c) SyntaxError
d) TypeError
Correct Answer: b) ValueError
Explanation:
compile() raises ValueError if the source string contains null bytes.

35. What exception is raised when 'eval()' receives an expression that exceeds maximum stack depth?

a) StackOverflowError
b) RecursionError
c) MemoryError
d) SyntaxError
Correct Answer: b) RecursionError
Explanation:
Deeply nested code structures evaluated via eval() will raise RecursionError when stack depth limits are reached.

36. Which exception is raised when 'sys.getrefcount()' is called on a non-object reference in C-API Python bindings?

a) TypeError
b) ReferenceError
c) SystemError
d) ValueError
Correct Answer: a) TypeError
Explanation:
sys.getrefcount expects a valid Python object reference; invalid types trigger a TypeError.

37. Which exception is raised when weakref proxy object is accessed after referent has been garbage collected?

a) AttributeError
b) ReferenceError
c) PointerError
d) NullPointerError
Correct Answer: b) ReferenceError
Explanation:
ReferenceError is raised when a weak reference proxy object is accessed after the underlying garbage collected object is dead.

38. What built-in function sets the hook for printing unhandled tracebacks to sys.stderr?

a) sys.excepthook
b) sys.settraceback
c) traceback.set_hook
d) builtins.error_hook
Correct Answer: a) sys.excepthook
Explanation:
sys.excepthook(type, value, traceback) is called whenever an uncaught exception occurs.

39. What happens if an exception is raised inside 'sys.excepthook' itself?

a) The program hangs indefinitely
b) The secondary exception is printed to stderr and program exits
c) sys.excepthook is called recursively until stack overflow
d) It is silently ignored
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.

40. Which module provides function 'traceback.format_exc()'?

a) sys
b) traceback
c) inspect
d) logging
Correct Answer: b) traceback
Explanation:
traceback.format_exc() formats the stack trace of the currently handled exception into a single string.

41. What is the return type of 'traceback.format_exception(e)'?

a) A single string
b) A list of strings formatted as stack trace lines
c) A dictionary of frame objects
d) A tuple of line numbers
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.

42. How can you disable default exception tracebacks in production using command-line flags?

a) python -O script.py
b) python -q script.py
c) python -W ignore script.py
d) Command-line flags cannot disable tracebacks; sys.excepthook must be modified
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.

43. Which of the following warning categories indicates that a feature is deprecated and will be removed in a future version?

a) UserWarning
b) DeprecationWarning
c) FutureWarning
d) RuntimeWarning
Correct Answer: b) DeprecationWarning
Explanation:
DeprecationWarning is targeted at developers to warn about features that are deprecated.

44. Which warning category is intended for end users of applications written in Python rather than developers?

a) DeprecationWarning
b) FutureWarning
c) SyntaxWarning
d) PendingDeprecationWarning
Correct Answer: b) FutureWarning
Explanation:
FutureWarning is intended to alert end users of applications about upcoming behavioral changes.

45. How can you convert warnings into fatal exceptions using the '-W' flag when running Python?

a) python -W error script.py
b) python -W fatal script.py
c) python -W raise script.py
d) python -W strict script.py
Correct Answer: a) python -W error script.py
Explanation:
Passing '-W error' treats all warnings as exceptions, causing them to raise rather than log.

46. Which context manager in the 'warnings' module isolates warning settings within a block?

a) warnings.catch_warnings()
b) warnings.isolate_warnings()
c) warnings.suppress()
d) warnings.trap()
Correct Answer: a) warnings.catch_warnings()
Explanation:
warnings.catch_warnings() temporarily redirects warnings and allows local filter modifications within a with-block.

47. What is the result of 'warnings.simplefilter("ignore")'?

a) Ignores all warnings globally across the process
b) Raises an Exception on next warning
c) Logs warnings to a separate file
d) Prints warnings only once per module
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.

48. Which statement about ExceptionGroup filtering using 'except*' is correct?

a) Matching exceptions are split off from the group and handled, while remaining exceptions propagate
b) An except* block always handles every exception in the group regardless of type
c) except* can only be used with built-in exceptions
d) except* replaces finally blocks in async code
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.

49. Can standard 'except Exception:' catch an ExceptionGroup containing non-Exception exceptions like KeyboardInterrupt?

a) Yes, ExceptionGroup always converts contents to Exception
b) No, if the group contains BaseException derivatives, BaseExceptionGroup is used and ignored by 'except Exception'
c) Yes, standard except handles BaseExceptionGroup
d) It causes a compilation crash
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.

50. What exception is raised when 'asyncio.gather()' fails without setting 'return_exceptions=True'?

a) The first exception encountered propagates immediately out of gather()
b) All exceptions are silently dropped
c) asyncio.AsyncError
d) TaskGroupError
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.

51. In Python 3.11+, what is the behavior of 'asyncio.TaskGroup' when an exception occurs in a child task?

a) It cancels remaining tasks in the group and raises an ExceptionGroup containing all failures
b) It ignores the error and leaves other tasks running
c) It restarts the failed task three times
d) It raises SystemExit
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.

52. What exception is raised when calling 'result()' on a cancelled asyncio Task?

a) asyncio.CancelledError
b) RuntimeError
c) ValueError
d) TaskError
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+).

53. In Python 3.8+, what class does 'asyncio.CancelledError' inherit from?

a) Exception
b) BaseException
c) RuntimeError
d) StandardError
Correct Answer: b) BaseException
Explanation:
In Python 3.8+, CancelledError inherits directly from BaseException so that accidental 'except Exception:' blocks do not catch it.

54. What exception is raised by 'asyncio.wait_for()' when specified timeout duration expires?

a) asyncio.TimeoutError
b) TimeoutError
c) socket.timeout
d) ClockError
Correct Answer: b) TimeoutError
Explanation:
In Python 3.11+, asyncio.TimeoutError is an alias for the built-in TimeoutError exception.

55. What exception occurs when invoking a method on an object that is None?

a) NullPointerError
b) AttributeError
c) TypeError
d) ValueError
Correct Answer: b) AttributeError
Explanation:
Attempting attribute access or method invocation on None raises 'AttributeError: 'NoneType' object has no attribute ...'.

56. What error occurs if you try to unpack a tuple of 2 elements into 3 variables like: x, y, z = (1, 2)?

a) IndexError
b) ValueError
c) UnpackError
d) TypeError
Correct Answer: b) ValueError
Explanation:
Mismatch in unpacking count produces 'ValueError: not enough values to unpack (expected 3, got 2)'.

57. What error occurs if you try to unpack a tuple of 4 elements into 2 variables without star expression?

a) ValueError
b) TypeError
c) OverflowError
d) IndexError
Correct Answer: a) ValueError
Explanation:
Unpacking too many values produces 'ValueError: too many values to unpack (expected 2)'.

58. Which exception is raised when passing an invalid literal to 'int()', like int('3.14')?

a) TypeError
b) ValueError
c) FormatError
d) ConversionError
Correct Answer: b) ValueError
Explanation:
int('3.14') raises 'ValueError: invalid literal for int() with base 10: '3.14''.

59. What error is raised if you attempt to call a integer like: x = 10; x()?

a) AttributeError
b) TypeError
c) ValueError
d) CallError
Correct Answer: b) TypeError
Explanation:
Invoking a non-callable object raises 'TypeError: 'int' object is not callable'.

60. What error is raised when performing bitwise operations on float numbers like: 3.14 & 2.0?

a) TypeError
b) ValueError
c) BitwiseError
d) ArithmeticError
Correct Answer: a) TypeError
Explanation:
Bitwise operations require integer operands; passing floats raises 'TypeError: unsupported operand type(s) for &'.

61. Which exception is raised when 'os.mkdir()' fails because target directory already exists?

a) FileExistsError
b) DirectoryExistsError
c) IOError
d) PathError
Correct Answer: a) FileExistsError
Explanation:
FileExistsError (subclass of OSError) is raised when creating a file or directory that already exists.

62. Which exception is raised when 'os.rmdir()' is called on a directory that is not empty?

a) DirectoryNotEmptyError
b) OSError
c) PermissionError
d) FileExistsError
Correct Answer: b) OSError
Explanation:
Removing a non-empty directory with os.rmdir raises an OSError (specifically ENOTEMPTY / Directory not empty).

63. What happens when an exception is raised inside a generator expression passed to 'any()'?

a) any() returns False
b) The exception propagates immediately out of any()
c) any() catches it and treats it as True
d) StopIteration is returned
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.

64. Which built-in module provides 'logging.exception()' method?

a) traceback
b) sys
c) logging
d) diagnostics
Correct Answer: c) logging
Explanation:
logging.exception(msg) logs a message with level ERROR and automatically appends exception traceback information.

65. Where should 'logging.exception()' typically be invoked?

a) Inside an except block
b) Inside a finally block
c) Before try block execution
d) Inside custom __init__ constructors
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.

66. What error is raised when trying to delete a module attribute that does not exist using 'delattr(mod, "name")'?

a) NameError
b) AttributeError
c) KeyError
d) DeleteError
Correct Answer: b) AttributeError
Explanation:
Deleting a non-existent attribute on any object via delattr() raises AttributeError.

67. What exception is raised when 'str.encode()' is called with an unknown encoding name?

a) UnicodeEncodeError
b) LookupError
c) ValueError
d) EncodingNotFoundError
Correct Answer: b) LookupError
Explanation:
Passing an invalid codec name (e.g., 'hello'.encode('foo')) raises 'LookupError: unknown encoding: foo'.

68. What is the relationship between LookupError and KeyError?

a) KeyError inherits from LookupError
b) LookupError inherits from KeyError
c) They are unrelated built-in exceptions
d) KeyError is an alias for LookupError
Correct Answer: a) KeyError inherits from LookupError
Explanation:
KeyError and IndexError both subclass LookupError.

69. What exception is raised when calling 'list.index(x)' when item x is not present in list?

a) IndexError
b) KeyError
c) ValueError
d) ItemNotFoundError
Correct Answer: c) ValueError
Explanation:
list.index(x) raises 'ValueError: x is not in list'.

70. What exception is raised by 'dict.pop(key)' when key is missing and no default value is provided?

a) IndexError
b) KeyError
c) ValueError
d) AttributeError
Correct Answer: b) KeyError
Explanation:
popping a non-existent key from dict without specifying a default argument raises KeyError.

71. What output is produced by 'dict.pop(key, None)' when key is missing?

a) Raises KeyError
b) Returns None without raising an exception
c) Raises ValueError
d) Returns False
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.

72. What exception is raised when attempting to open a named pipe or device file with invalid permissions?

a) PermissionError
b) DeviceError
c) IOError
d) SystemError
Correct Answer: a) PermissionError
Explanation:
PermissionError is raised when system permission settings prevent performing requested file/device operation.

73. Which built-in exception is raised when trying to write to a read-only file stream?

a) ReadOnlyError
b) io.UnsupportedOperation
c) PermissionError
d) ModeError
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.

74. Which error is raised when calling 'next()' on an iterator that has already completed?

a) StopIteration
b) IteratorError
c) IndexError
d) ValueError
Correct Answer: a) StopIteration
Explanation:
StopIteration is raised by iterators to signal that there are no remaining elements.

75. What happens if a generator function raises 'StopIteration' explicitly in Python 3.7+?

a) It closes generator normally
b) It is converted into a RuntimeError
c) It is re-raised as StopIteration
d) It causes a Warning
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.

76. Which statement about '__del__' destructor exception handling is correct?

a) Exceptions in __del__ propagate to main caller and crash script
b) Exceptions in __del__ are ignored and written to sys.unraisablehook / stderr
c) Exceptions in __del__ are automatically caught by try-except blocks
d) Destructors cannot raise exceptions under any condition
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.

77. Which exception is raised when executing 'exec()' with code string having invalid syntax?

a) ExecError
b) SyntaxError
c) ValueError
d) TypeError
Correct Answer: b) SyntaxError
Explanation:
exec() compiles and executes Python code strings at runtime and raises SyntaxError if syntax parsing fails.

78. Which built-in exception occurs when attempting to convert an out-of-range integer to bytes using 'int.to_bytes()'?

a) ValueError
b) OverflowError
c) TypeError
d) RangeError
Correct Answer: b) OverflowError
Explanation:
int.to_bytes() raises OverflowError if integer is too large to fit in specified byte length.

79. What exception is raised when multiplying a list by a float, such as: [1, 2] * 2.5?

a) ValueError
b) TypeError
c) FloatError
d) MultiplyError
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''.

80. What exception is raised when trying to format a string with missing position keys in format(), e.g. '{0} {1}'.format('a')?

a) KeyError
b) IndexError
c) ValueError
d) FormatError
Correct Answer: b) IndexError
Explanation:
Positional formatting missing required arguments raises 'IndexError: Replacement index 1 out of range for positional args tuple'.

81. What exception is raised when named format placeholders are missing, e.g. '{name}'.format()?

a) KeyError
b) IndexError
c) NameError
d) ValueError
Correct Answer: a) KeyError
Explanation:
Keyword string formatting missing arguments raises KeyError for missing key.

82. What built-in exception is raised when creating a class that inherits from multiple classes with conflicting metaclasses?

a) ClassError
b) TypeError
c) MetaclassError
d) InheritanceError
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'.

83. Which exception is raised when 'ctypes' module encounters NULL pointer dereference?

a) NullPointerError
b) ValueError
c) OSError
d) Segmentation Fault / Access Violation (often fatal or raises OSError depending on OS)
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.

84. Which exception is raised by 'tempfile.NamedTemporaryFile' when directory creation fails?

a) TempFileError
b) FileNotFoundError
c) OSError
d) DirectoryError
Correct Answer: c) OSError
Explanation:
Subclasses of OSError are raised when OS-level file or directory creation in temp directory fails.

85. What exception is raised when trying to slice a set object like: s = {1, 2}; s[0:1]?

a) IndexError
b) TypeError
c) KeyError
d) SliceError
Correct Answer: b) TypeError
Explanation:
Sets are unindexed collections; attempting index slicing raises 'TypeError: 'set' object is not subscriptable'.

86. What exception is raised when trying to add an unhashable object like a list into a set?

a) ValueError
b) TypeError
c) SetError
d) HashError
Correct Answer: b) TypeError
Explanation:
Adding unhashable objects to set raises 'TypeError: unhashable type: 'list''.

87. Which exception is raised when using a mutable object as a dictionary key?

a) KeyError
b) TypeError
c) ValueError
d) DictError
Correct Answer: b) TypeError
Explanation:
Dictionary keys must be hashable; mutable objects like lists or dicts raise 'TypeError: unhashable type'.

88. What exception is raised when trying to modify a tuple using index assignment, e.g. t = (1, 2); t[0] = 5?

a) ValueError
b) TypeError
c) ImmutableError
d) IndexError
Correct Answer: b) TypeError
Explanation:
Tuples are immutable; item assignment raises 'TypeError: 'tuple' object does not support item assignment'.

89. What exception is raised when trying to append to a tuple, e.g. t.append(3)?

a) AttributeError
b) TypeError
c) ValueError
d) MutationError
Correct Answer: a) AttributeError
Explanation:
Tuples do not have an append method; attempting to call non-existent method raises AttributeError.

90. What exception is raised when calling 'bytes.fromhex()' with an odd length string?

a) HexError
b) ValueError
c) TypeError
d) LengthError
Correct Answer: b) ValueError
Explanation:
Hexadecimal bytes conversion requires pairs of digits; odd-length strings raise 'ValueError: non-hexadecimal number found / odd-length string'.

91. Which exception is raised when calling 'math.factorial()' with a negative number?

a) OverflowError
b) ValueError
c) TypeError
d) DomainError
Correct Answer: b) ValueError
Explanation:
Factorial is defined for non-negative integers; negative inputs raise 'ValueError: factorial() not defined for negative values'.

92. Which exception is raised when calling 'math.factorial()' with a float value like 5.5?

a) ValueError
b) TypeError
c) FloatError
d) ArithmeticError
Correct Answer: a) ValueError
Explanation:
In modern Python math module, math.factorial(5.5) raises ValueError (factorial() only accepts integral values).

93. What exception is raised when 'signal.signal()' is called from a non-main thread?

a) ThreadError
b) ValueError
c) SignalError
d) PermissionError
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'.

94. What exception is raised when 'os.kill()' fails due to non-existent process ID?

a) ProcessLookupError
b) PIDError
c) FileNotFoundError
d) SystemError
Correct Answer: a) ProcessLookupError
Explanation:
ProcessLookupError (subclass of OSError) is raised when given process ID does not exist.

95. What error is raised when trying to pop from a deque object that is empty using 'deque.pop()'?

a) KeyError
b) IndexError
c) ValueError
d) EmptyError
Correct Answer: b) IndexError
Explanation:
Popping from an empty collections.deque raises 'IndexError: pop from an empty deque'.

96. What error is raised by 'queue.Queue.get_nowait()' on an empty thread-safe Queue?

a) IndexError
b) queue.Empty
c) StopIteration
d) ValueError
Correct Answer: b) queue.Empty
Explanation:
Non-blocking fetch on empty Queue raises the queue module's exception 'queue.Empty'.

97. What error is raised by 'queue.Queue.put_nowait()' on a full bounded Queue?

a) OverflowError
b) queue.Full
c) MemoryError
d) BufferError
Correct Answer: b) queue.Full
Explanation:
Non-blocking put on full Queue raises the queue module's exception 'queue.Full'.

98. Which built-in exception is raised when an encoding operation fails during string processing?

a) UnicodeEncodeError
b) EncodingFailedError
c) ValueError
d) StringEncodeError
Correct Answer: a) UnicodeEncodeError
Explanation:
UnicodeEncodeError is raised when converting unicode characters into byte encodings that do not support those characters.

99. What is the relationship between UnicodeEncodeError and UnicodeError?

a) UnicodeEncodeError inherits from UnicodeError
b) UnicodeError inherits from UnicodeEncodeError
c) They are sibling exceptions under TypeError
d) They are identical classes
Correct Answer: a) UnicodeEncodeError inherits from UnicodeError
Explanation:
UnicodeEncodeError is a subclass of UnicodeError (which is a subclass of ValueError).

100. What error is raised when passing an invalid argument to 'sys.setrecursionlimit()' such as 0 or negative values?

a) ValueError
b) RecursionError
c) TypeError
d) OverflowError
Correct Answer: a) ValueError
Explanation:
Setting limit below minimal threshold raises 'ValueError: limit must be > 0'.

101. What is the result of catching 'BaseException' in a try-except block?

a) Catches standard application errors but ignores system exits
b) Catches absolutely all exceptions including SystemExit, KeyboardInterrupt, and GeneratorExit
c) Causes a syntax error
d) Catches only user-defined exceptions
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.

102. Why is inheriting custom exceptions from 'BaseException' directly usually discouraged?

a) It prevents exceptions from being caught by standard 'except Exception:' blocks
b) It slows down performance
c) It causes immediate process termination
d) BaseException cannot be subclassed
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.

103. Which of the following describes exception safety in Python code best?

a) Ensuring program never raises exceptions
b) Ensuring resources are safely cleaned up (e.g. via context managers or finally) even when exceptions occur
c) Wrapping entire codebase in one top-level try-except
d) Disabling garbage collection during exceptions
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.
← Previous: Python Decorators & Generators MCQs
Next →: Python File Handling MCQs
Java Functions MCQs

Java Functions MCQs

In Java, functions are formally known as methods and serve as modular blocks of reusable code encapsulated within classes. A…

By 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…

By MCQs Generator
JavaScript Loops MCQs

JavaScript Loops MCQs

Iteration structures in JavaScript allow developers to execute code blocks repeatedly based on dynamic boolean conditions. Standard loops such as…

By MCQs Generator