Exception Handling in Python – Class 12 Computer Science MCQs
In this post, you will find important Class 12 Computer Science MCQs from Chapter 1 – Exception Handling in Python, prepared according to the latest syllabus.
These multiple choice questions (MCQs) cover all key concepts such as try, except, else, and finally blocks, exception types, and error-handling flow in Python programs.
Each question is explained in detail to help you understand why a particular answer is correct. These questions are very useful for Class 12 Board Exams, Python practicals, and school-level tests.
What You Will Learn
- Concept and importance of exception handling in Python
- Working of try, except, else, and finally blocks
- Flow of control when an exception occurs
- Common Python exceptions like
ZeroDivisionError,ValueError, andNameError - Exam-style MCQs with detailed reasoning and examples
Why These MCQs Are Important
These MCQs are designed to test both your conceptual understanding and practical knowledge of exception handling.
By solving them, you’ll strengthen your understanding of Python’s error-handling mechanisms and gain confidence for your Class 12 Board Exam and Python practical assessments.
1. What is an exception in Python?
(A) An error detected only before program execution
(B) An error that occurs during program execution and can be handled
(C) A logical error that occurs due to incorrect reasoning
(D) A type of syntax error
Answer: (B) An error that occurs during program execution and can be handled
Explanation
Explanation:
An exception in Python is an error that occurs while the program is running, not before execution.
Unlike syntax errors, which are detected when the code is being parsed, exceptions arise during runtime and can be handled using try-except blocks.Handling exceptions allows the program to continue executing instead of abruptly stopping.
Common examples include:
IndexError– accessing an invalid list indexZeroDivisionError– division by zeroNameError– using an undefined variableFileNotFoundError– trying to open a file that doesn’t existExample:
try:
x = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
2. Which of the following is NOT a type of error in Python?
(A) Syntax Error
(B) Runtime Error
(C) Logical Error
(D) Compilation Error
Answer: (D) Compilation Error
Explanation
Explanation:
Python is an interpreted language, which means the source code is executed line by line by the Python interpreter.
There is no separate compilation stage as in compiled languages such as C or C++.Therefore, Compilation Error does not occur in Python.
The main types of errors in Python are:
- Syntax Errors – mistakes in the code structure or grammar.
Example:print "Hello" # Missing parentheses → SyntaxError- Runtime Errors (Exceptions) – errors that occur while the program is running.
Example:print(10 / 0) # ZeroDivisionError- Logical Errors – flaws in the program logic that produce incorrect output but do not stop execution.
Example:# Wrong formula used area = 2 * 3.14 * r # Logic error instead of 3.14 * r * rSummary Table
Error Type When Occurs Example Detected By Interpreter? Syntax Error Before execution print "Hi"Yes Runtime Error (Exception) During execution 10/0Yes Logical Error During execution wrong formula No Compilation Error — — Not applicable in Python
3. What happens when a syntax error is encountered in Python?
(A) The program executes partially and ignores the error
(B) The interpreter stops execution until the error is corrected
(C) The program automatically fixes the syntax error
(D) Syntax errors occur only during runtime
Answer: (B) The interpreter stops execution until the error is corrected
Explanation
Explanation:
A syntax error occurs when the code violates Python’s grammatical rules or structure.
Such errors are also called parsing errors because they are detected during the parsing stage, before the program starts executing.When a syntax error is encountered, the Python interpreter halts immediately and displays an error message indicating the line and nature of the mistake.
The program cannot be executed until all syntax errors are fixed.Example:
print("Hello"Output:
SyntaxError: unexpected EOF while parsingThe interpreter stops execution and reports the issue — the program will not run until the missing parenthesis is corrected.
Key Point for Exam:
Syntax errors are detected before program execution and must be corrected before the interpreter can run the code.
4. Which of the following statements is TRUE about exceptions?
(A) Exceptions occur only when there is a syntax error
(B) Exceptions can be handled to prevent abnormal termination of the program
(C) Exceptions are ignored by Python by default
(D) Exceptions are the same as logical errors
Answer: (B) Exceptions can be handled to prevent abnormal termination of the program
Explanation
Explanation:
Exceptions occur during program execution, even if the syntax of the code is correct.
They are runtime errors that interrupt the normal flow of the program.
However, Python provides exception handling mechanisms usingtryandexceptblocks, which allow the program to handle these errors gracefully instead of crashing.Example:
try: a = 10 b = 0 print(a / b) except ZeroDivisionError: print("Cannot divide by zero.")Output:
Cannot divide by zero.Here, the exception (
ZeroDivisionError) is handled, preventing the program from terminating abnormally.Key Point for Exam:
Exceptions can be caught and handled using
try-exceptblocks, allowing the program to continue running normally..
5. Which of the following best describes a syntax error?
(A) An error due to incorrect logic in the code
(B) An error detected when the rules of Python are not followed
(C) An error due to improper handling of runtime exceptions
(D) An error caused by dividing by zero
Answer: (B) An error detected when the rules of Python are not followed
Explanation
Explanation:
A syntax error occurs when the programmer does not follow Python’s grammatical or structural rules.
These errors are detected before program execution — during the parsing stage — and prevent the code from running until they are corrected.Common causes of syntax errors include:
- Missing or mismatched parentheses
- Incorrect indentation
- Misspelled keywords or punctuation mistakes
Example:
if True print("Hello")Output:
SyntaxError: expected ':'The interpreter detects the missing colon (
:) and stops execution until it is fixed.Key Point for Exam:
A syntax error occurs when Python’s grammar or structure is violated and is detected before execution begins.
6. What happens when a syntax error is encountered in Python shell mode?
(A) The program executes partially with incorrect results
(B) Python displays the error name and a brief description
(C) Python automatically fixes the syntax and executes
(D) The program ignores the syntax error and continues
Answer: (B) Python displays the error name and a brief description
Explanation
Explanation:
When using the Python shell (interactive mode), the interpreter executes each line immediately after you press Enter.
If a syntax error is detected, Python instantly reports it, showing both the error type (usuallySyntaxError) and a short description of the issue.The program does not execute until the error is corrected.
Example (in Shell mode):
>>> print "Hello"Output:
File "<stdin>", line 1 print "Hello" ^^^^^^^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello")?Python clearly indicates the type of error (
SyntaxError) and gives a brief explanation suggesting how to fix it.Key Point for Exam:
In shell mode, Python immediately displays the error name and a short message describing the syntax mistake
7. Which of the following statements is TRUE about syntax errors in script mode?
(A) Script mode errors are ignored if shell mode is error-free
(B) An error message appears showing the error name and description
(C) Script mode automatically corrects syntax errors
(D) Syntax errors only occur when the program executes successfully
Answer: (B) An error message appears showing the error name and description
Explanation
Explanation:
When a Python program is executed in script mode, the entire file is checked for syntax correctness before execution.
If any syntax error is found, Python does not run the script and instead displays an error message showing:
- the type of error (e.g.,
SyntaxError)- and a brief description of the problem
In environments like IDLE, this message may appear in a dialog box, whereas in a terminal or editor, it appears in the console output.
Example:
print("Hello"Output:
File "example.py", line 1 print("Hello" ^ SyntaxError: unexpected EOF while parsingKey Point for Exam:
In script mode, Python halts execution and displays an error message (or dialog in IDLE) describing the syntax error before running the program.
8. What does the following Python statement in shell mode produce?
marks>20:
print "GOOD SCORE"
(A) Prints “GOOD SCORE”
(B) Triggers a runtime error
(C) Triggers a syntax error
(D) Executes without any error
Answer: (C) Triggers a syntax error
Explanation
Explanation:
This code contains two syntax errors:
- The colon (:) is incorrectly used — it should appear after a valid control statement such as
if,for, orwhile.- The print statement in Python 3 requires parentheses — it should be written as
print("GOOD SCORE").Because of these syntax issues, the Python interpreter detects the error before execution and raises a
SyntaxError.Example (in shell mode):
>>> marks > 20: File "<stdin>", line 1 marks > 20: ^ SyntaxError: invalid syntaxKey Point for Exam:
Python checks for syntax errors before execution; misplaced colons or missing parentheses cause a
SyntaxErrorimmediately.
9. In Python 3.x, what is the correct way to print a message?
(A) print "Hello World"
(B) print("Hello World")
(C) echo("Hello World")
(D) printf("Hello World")
Answer: (B) print("Hello World")
Explanation
Explanation:
In Python 3,
Therefore, parentheses are required when calling it.Using the old Python 2 syntax (
print "Hello World") results in a SyntaxError because it violates Python 3 syntax rules.Example:
# Correct (Python 3) print("Hello World") # Incorrect (Python 2 style) print "Hello World" # ❌ SyntaxErrorOutput for incorrect version:
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello World")?Key Point for Exam:
In Python 3,
print("message").
10. Which of the following best describes the role of Python in reporting syntax errors?
(A) Python ignores syntax errors and runs the program
(B) Python shows a brief error name and suggestion to rectify it
(C) Python automatically fixes syntax errors
(D) Python converts syntax errors into runtime errors
Answer: (B) Python shows a brief error name and suggestion to rectify it
Explanation
Explanation:
When a syntax error occurs, the Python interpreter stops execution immediately and displays a clear error message.
This message typically includes:
- The error type, such as
SyntaxError.- A short description of what went wrong.
- In many cases, a suggestion on how to fix the problem (for example, missing parentheses or colons).
This built-in feedback helps programmers quickly locate and correct syntax issues before running the code successfully.
Example:
print "Hello"Output:
File "<stdin>", line 1 print "Hello" ^^^^^^^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello")?Key Point for Exam:
Python immediately reports syntax errors with the error name, a short description, and sometimes a helpful suggestion to correct the mistake.
11. What is an exception in Python?
(A) A statement that is syntactically incorrect
(B) An error that occurs during program execution
(C) A method that always executes successfully
(D) A variable that stores numeric data only
Answer: (B) An error that occurs during program execution
Explanation
Explanation:
An exception in Python is an error that occurs while the program is running, even though the syntax of the code is correct.
When such an event happens, Python raises an exception to indicate the error condition.If the exception is not handled, it causes abnormal termination of the program.
However, exceptions can be handled gracefully usingtryandexceptblocks to ensure smooth program execution.Common examples:
ZeroDivisionError– dividing by zeroFileNotFoundError– trying to open a non-existent fileNameError– using an undefined variableExample:
try: print(10 / 0) except ZeroDivisionError: print("Error: Cannot divide by zero.")Output:
Error: Cannot divide by zero.Key Point for Exam:
An exception is a runtime error that can be handled using
try-exceptstatements to prevent the program from crashing.
12. Which of the following is TRUE about exceptions?
(A) All exceptions occur due to syntax errors
(B) Exceptions only occur in Python 2.x
(C) Exceptions may occur even when the code is syntactically correct
(D) Exceptions are always caused by incorrect indentation
Answer: (C) Exceptions may occur even when the code is syntactically correct
Explanation
Explanation:
Exceptions are runtime errors that occur while the program is executing, even if the syntax is completely valid.
They arise when an operation or statement fails during execution.Examples:
ZeroDivisionError→ Dividing by zeroFileNotFoundError→ Trying to open a non-existent fileNameError→ Using an undefined variableThese errors can be handled using
tryandexceptblocks to prevent program crashes.Key Point for Exam:
Exceptions occur after successful compilation but during execution, unlike syntax errors which are detected before execution.
13. What are built-in exceptions in Python?
(A) Exceptions created by the programmer
(B) Commonly occurring exceptions predefined in Python
(C) Errors that never occur during execution
(D) Syntax errors in the program
Answer: (B) Commonly occurring exceptions predefined in Python
Explanation
Explanation:
Built-in exceptions are predefined error classes in Python that represent common runtime errors.
They are part of Python’s standard library and are automatically raised by the interpreter when specific conditions fail during program execution.Examples include:
ZeroDivisionError– dividing by zeroNameError– using an undefined variableTypeError– performing an operation on incompatible data typesValueError– passing an invalid value to a functionEOFError– reading beyond the end of a fileKey Point for Exam:
Built-in exceptions are ready-made error classes provided by Python to handle frequent runtime issues efficiently.
14. Which exception is raised when a division by zero is attempted?
(A) NameError
(B) ZeroDivisionError
(C) ValueError
(D) SyntaxError
Answer: (B) ZeroDivisionError
Explanation
Explanation:
When a program attempts to divide any number by zero, Python immediately raises a ZeroDivisionError.
This is a runtime exception, meaning it occurs while the program is executing, not during compilation or parsing.Example:
print(10 / 0) # Raises ZeroDivisionErrorTo prevent the program from crashing, it can be handled using a
try-exceptblock:try: print(10 / 0) except ZeroDivisionError: print("Division by zero is not allowed.")Key Point for Exam:
ZeroDivisionErroroccurs only at runtime when a division operation’s denominator is zero.
15. What exception occurs when a variable is used without being defined?
(A) NameError
(B) IndexError
(C) TypeError
(D) OverflowError
Answer: (A) NameError
Explanation
Explanation:
A NameError occurs when Python encounters a variable or identifier that has not been defined in the current scope.
This means the interpreter cannot find the variable name in memory during execution.Example:
print(x) # x is not defined → Raises NameErrorTo fix this, the variable must be defined before use:
x = 10 print(x) # Output: 10Key Point for Exam:
NameErrorindicates that a variable or identifier is being used before it is defined or imported.
16. Which exception occurs when the index of a sequence is out of range?
(A) IndexError
(B) KeyError
(C) ValueError
(D) TypeError
Answer: (A) IndexError
Explanation
Explanation:
An IndexError is raised when a program tries to access an element of a sequence (like a list, tuple, or string) using an index that is outside the valid range.Example:
lst = [1, 2, 3] print(lst[5]) # Raises IndexError: list index out of rangeThe valid indices for
lstare0, 1, 2.
Accessinglst[5]triggers an IndexError because the fifth index does not exist.Key Point for Exam:
IndexErroroccurs when a sequence is accessed using an invalid index, exceeding its valid range.
17. Which of the following exceptions is raised when a program reaches end-of-file without reading data?
(A) EOFError
(B) ImportError
(C) SyntaxError
(D) ValueError
Answer: (A) EOFError
Explanation
Explanation:
An EOFError occurs when Python expects input (for example, via theinput()function) but reaches the end-of-file (EOF) without receiving any data.
This commonly happens when reading from files or when input is terminated unexpectedly.Example:
# Expecting user input data = input("Enter something: ")If the input stream ends (e.g., in a file or redirected input) without providing data, Python raises:
EOFError: EOF when reading a lineKey Point for Exam:
EOFErroroccurs when input is expected but the end-of-file is reached before any data is read.
18. What are user-defined exceptions in Python?
(A) Exceptions created automatically by Python
(B) Exceptions that occur due to syntax errors
(C) Exceptions created by the programmer to suit specific requirements
(D) Exceptions that never need handling
Answer: (C) Exceptions created by the programmer to suit specific requirements
Explanation
Explanation:
User-defined exceptions are custom exceptions created by programmers to handle specific situations that built-in exceptions cannot adequately address.
This allows the programmer to provide more precise and meaningful error handling in a program.Example:
# Define a custom exception class NegativeValueError(Exception): pass def check_value(x): if x < 0: raise NegativeValueError("Negative values are not allowed") # Usage try: check_value(-5) except NegativeValueError as e: print("Error:", e)Output:
Error: Negative values are not allowedKey Point for Exam:
User-defined exceptions let programmers create custom error types for situations not covered by Python’s built-in exceptions.
19. What happens when an exception is raised in Python using the raise statement?
(A) The program continues executing the next statements in the current block
(B) The normal flow of the program is interrupted and control is transferred to the exception handler
(C) Python ignores the exception
(D) The exception automatically terminates the Python interpreter
Answer: (B) The normal flow of the program is interrupted and control is transferred to the exception handler
Explanation
Explanation:
When an exception is raised using theraisestatement:
- Python immediately stops executing the current block of code.
- The control jumps to the corresponding exception handler (
exceptblock).- Any statements after the
raisein the same block are not executed.This ensures that errors are properly handled without letting the program continue in an unstable state.
Example:
try: raise Exception("OOPS!! An Exception has occurred") print("This line will not execute") except Exception as e: print("Exception caught:", e)Output:
Exception caught: OOPS!! An Exception has occurredHere, the line after
raiseis skipped, and control moves directly to theexceptblock.Key Point for Exam:
The
raisestatement interrupts normal execution and transfers control to the appropriate exception handler.
20. Which of the following is the correct syntax of the raise statement in Python?
(A) raise exception-name[(optional argument)](
(B) raise exception-name: optional argument
(C) raise (exception-name, optional argument)
(D) raise exception-name optional argument
Answer: (A) raise exception-name[(optional argument)]
Explanation
Explanation:
Theraisestatement is used to explicitly throw an exception in Python.
- The exception name specifies the type of error.
- The optional argument is usually a string describing the error message.
Example:
raise Exception("OOPS!! An Exception has occurred")Output:
Traceback (most recent call last): ... Exception: OOPS!! An Exception has occurredHere, Python raises an
Exceptionand displays the error message provided as the argument.Key Point for Exam:
Use
raise Exception("message")to explicitly trigger an exception with a custom message.
21. What type of exceptions can be raised using the raise statement?
(A) Only built-in exceptions
(B) Only user-defined exceptions
(C) Both built-in and user-defined exceptions
(D) Syntax errors only
Answer: (C) Both built-in and user-defined exceptions
Explanation
Explanation:
Theraisestatement in Python can be used to manually trigger both:
- Built-in exceptions — such as
IndexError,ValueError, orZeroDivisionError.- User-defined exceptions — custom exceptions created by the programmer to handle specific situations.
Examples:
# Raising a built-in exception raise IndexError("List index out of range") # Raising a user-defined exception class MyError(Exception): pass raise MyError("Custom exception raised by user")Both examples stop program execution and display the corresponding error message until handled using a
try-exceptblock.Key Point for Exam:
The
raisestatement can generate any exception type, whether predefined (built-in) or created by the user (custom).
22. What will happen in the following code?
numbers = [1, 2, 3]
length = 5
if length > len(numbers):
raise IndexError
print("NO EXECUTION")
(A) IndexError is raised and “NO EXECUTION” is printed
(B) IndexError is raised and “NO EXECUTION” is not printed
(C) Nothing happens and “NO EXECUTION” is printed
(D) SyntaxError occurs
Answer: (B) IndexError is raised and “NO EXECUTION” is not printed
Explanation
Explanation:
The value oflengthis greater than the length of the listnumbers.
When the conditionlength > len(numbers)evaluates toTrue, Python executes theraise IndexErrorstatement.
- The
raisestatement immediately interrupts the normal flow of the program.- Any statements after
raisein the same block (likeprint("NO EXECUTION")) are not executed.Hence, an
IndexErroris raised, and the message"NO EXECUTION"is not displayed.Key Point for Exam:
The
raisestatement halts execution instantly; code written after it in the same block will never run.
23. What is the purpose of providing an argument while raising an exception in Python?
(A) To ignore the exception
(B) To display a custom message describing the error
(C) To automatically fix the error
(D) To convert it into a syntax error
Answer: (B) To display a custom message describing the error
Explanation
Explanation:
When raising an exception using theraisestatement, an optional argument can be provided — usually a string message.
This message helps describe the cause of the error, making debugging easier and output more meaningful.Example:
raise Exception("OOPS!! An Exception has occurred")Output:
Exception: OOPS!! An Exception has occurredHere, the message
"OOPS!! An Exception has occurred"clearly explains why the exception was raised.Key Point for Exam:
The argument in the
raisestatement provides a custom error message that helps identify the cause of the exception.
24. What information does a Python stack traceback provide when an exception is raised?
(A) The value of variables in the program only
(B) The sequence of function calls leading to the exception
(C) The time at which the exception occurred
(D) The solution to fix the exception automatically
Answer: (B) The sequence of function calls leading to the exception
Explanation
Explanation:
When an exception occurs, Python displays a stack traceback — a structured message showing where and how the error happened.
It lists the sequence of function calls (from first to last) that led to the exception.
The last line in the traceback indicates the exact location where the error was raised.This information helps programmers debug the code and trace the source of the problem.
Example:
numbers = [40, 50, 60, 70] length = 10 if length > len(numbers): raise IndexErrorOutput:
Traceback (most recent call last): File "<pyshell#7>", line 4, in <module> raise IndexError IndexErrorKey Point for Exam:
A stack traceback shows the chain of function calls that led to an exception, helping in error tracking and debugging.
25. What is the purpose of the assert statement in Python?
(A) To ignore an error and continue program execution
(B) To test an expression and raise an exception if the test fails
(C) To define a new exception
(D) To display a stack traceback
Answer: (B) To test an expression and raise an exception if the test fails
Explanation
Explanation:
Theassertstatement is used for debugging and validation.
It checks whether a condition (expression) is True.
- If the condition is True, the program continues normally.
- If the condition is False, Python raises an
AssertionErrorwith an optional custom message.This is often used to ensure that certain conditions hold true during program execution.
Syntax:
assert Expression[, "Optional error message"]Example:
def negativecheck(number): assert number >= 0, "OOPS... Negative Number" negativecheck(-5)Output:
AssertionError: OOPS... Negative NumberKey Point for Exam:
The
assertstatement acts as a self-check tool to verify assumptions in your code. If the assumption fails, it raises an AssertionError automatically.
26. In which situations is it recommended to use the assert statement in Python?
(A) For handling runtime errors like file not found
(B) For testing valid input values at the start of a function
(C) For syntax error checking
(D) For terminating the Python interpreter
Answer: (B) For testing valid input values at the start of a function
Explanation
Explanation:
Theassertstatement is primarily used for testing assumptions and validating input conditions during development.
It ensures that certain conditions hold true before the program proceeds further.
If the condition fails, anAssertionErroris raised immediately, helping developers identify logic or input errors early.Example:
def square_root(n): assert n >= 0, "Negative input not allowed" return n ** 0.5 square_root(-4)Output:
AssertionError: Negative input not allowedKey Point for Exam:
Use
assertfor internal checks and debugging, not for handling runtime or user-generated errors.
27. What happens when the expression in an assert statement evaluates to True?
(A) Python raises an AssertionError
(B) Python continues executing the program normally
(C) Python stops execution immediately
(D) Python ignores all exceptions
Answer: (B) Python continues executing the program normally
Explanation
Explanation:
When the condition (expression) in anassertstatement evaluates to True, Python simply does nothing — it proceeds to execute the next lines of code normally.
TheAssertionErroris raised only if the condition evaluates to False.Example:
x = 10 assert x > 0, "x must be positive" print("Program continues")Output:
Program continuesKey Point for Exam:
The
assertstatement is a debugging aid — it only interrupts execution when the tested condition is False.
28. What happens when an assert statement fails in Python?
(A) The program continues execution without any error
(B) An AssertionError is raised and subsequent statements are not executed
(C) Python automatically corrects the value and continues
(D) The program terminates without any error message
Answer: (B) An AssertionError is raised and subsequent statements are not executed
Explanation
Explanation:
When the condition in anassertstatement evaluates to False, Python immediately raises anAssertionError.
This halts execution of the current block or function, and no statements after the failed assertion are executed.
It is mainly used to validate assumptions and check preconditions in code.Example:
def negativecheck(number): assert number >= 0, "OOPS... Negative Number" print(negativecheck(100)) # Works fine print(negativecheck(-350)) # Raises AssertionErrorOutput:
None Traceback (most recent call last): AssertionError: OOPS... Negative NumberKey Point for Exam:
When an
assertfails, Python raises anAssertionErrorand stops execution immediately — it never continues to the next line.
29. What is the primary purpose of exception handling in Python?
(A) To write programs faster
(B) To avoid program crashes and provide meaningful messages to the user
(C) To increase program execution speed
(D) To detect syntax errors
Answer: (B) To avoid program crashes and provide meaningful messages to the user
Explanation
Explanation:
Exception handling in Python ensures that runtime errors (like division by zero, file not found, etc.) do not cause the program to crash unexpectedly.
Instead, programmers can catch these exceptions and handle them gracefully — for example, by showing a helpful message or taking corrective action.
This improves the user experience and program stability.Example:
try: num = int(input("Enter a number: ")) result = 10 / num print("Result:", result) except ZeroDivisionError: print("Cannot divide by zero!")Output (if user enters 0):
Cannot divide by zero!Key Point for Exam:
Exception handling doesn’t fix errors — it manages them so the program can respond gracefully instead of crashing.
30. Why is exception handling considered important across programming languages like Python, C++, and Java?
(A) Because it helps in debugging syntax errors
(B) Because it helps capture runtime errors and prevents program crashes
(C) Because it allows faster execution of loops
(D) Because it automatically optimizes memory usage
Answer: (B) Because it helps capture runtime errors and prevents program crashes
Explanation
Explanation:
Exception handling is an essential feature in almost all modern programming languages, including Python, C++, and Java.
It allows the program to detect, handle, and recover from unexpected runtime errors — such as division by zero, invalid inputs, or missing files — without crashing.This leads to:
- Better program stability
- Improved user experience
- Easier debugging and maintenance
Example (Python):
try: file = open("data.txt", "r") except FileNotFoundError: print("File not found! Please check the filename.")Output (if file missing):
File not found! Please check the filename.Key Point for Exam:
Exception handling enhances robustness and fault tolerance, which is why it’s a core concept across multiple programming languages
31. In the output of Program 1-1 using assert statement, why is None printed before the AssertionError?
(A) Because the function negativecheck does not return any value
(B) Because assert always prints None
(C) Because the input is negative
(D) Because Python automatically inserts None
Answer: (A) Because the function negativecheck does not return any value
Explanation
Explanation
- Default return value in Python functions:
- In Python, if a function does not have a
returnstatement, it implicitly returnsNone.- Example:
def foo(): pass print(foo()) # Output: None- Behavior of
negativecheckfunction:
- Suppose Program 1-1 defines the function as:
def negativecheck(x): assert x >= 0, "Negative value not allowed"- When you call
negativecheck(100):
- The assertion passes because 100 ≥ 0.
- The function has no return statement, so Python returns
None.- If you print the function call,
Noneappears in the output.- When AssertionError occurs:
- If the input is negative, e.g.,
negativecheck(-5):
- The assertion fails.
- Python immediately raises an
AssertionError.- The function never reaches a return statement, so
Noneis not printed.- Why other options are wrong:
- (B)
assertdoes not printNone.- (C) Negative input triggers only AssertionError, not
None.- (D) Python does not automatically insert
None; it only returnsNonefor functions without an explicit return.Key Point for Exam:
Noneappears because the function does not explicitly return a value, and Python automatically returnsNonein such cases.- AssertionError occurs before return if the input violates the assertion, so
Noneis not printed then.
32. Why does Python categorize exceptions into distinct types?
(A) To make syntax errors disappear automatically
(B) To allow specific exception handlers for each type of error
(C) To reduce program execution time
(D) To eliminate the need for user input
Answer: (B) To allow specific exception handlers for each type of error
Explanation
Explanation:
Reason for categorizing exceptions:
- Python categorizes exceptions into different types so that programmers can write specific exception handlers for each type of error.
- This allows different types of errors to be handled differently.
Benefits:
- Keeps the main logic of the program separate from error-handling code.
- Makes programs more robust, readable, and maintainable.
Example:
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") try: file = open("data.txt", "r") except FileNotFoundError: print("File not found!")
ZeroDivisionErroris handled separately fromFileNotFoundError.Key Point for Exam:
Each type of exception can have a custom handler, improving program robustness.
Categorizing exceptions allows precise control over error handling.
33. Which of the following best describes the role of an exception object in Python?
(A) It corrects the error automatically
(B) It contains information about the error, such as its type, file name, and position in the program
(C) It prints the output of the program
(D) It stops the program without explanation
Answer: (B) It contains information about the error, such as its type, file name, and position in the program
Explanation
Explanation:
Role of an exception object
- When an error occurs in Python, the interpreter creates an exception object.
- This object contains detailed information about the error.
Information contained in an exception object:
- Type of the error (e.g.,
ZeroDivisionError,FileNotFoundError)- Error message describing the cause
- File name where the error occurred
- Line number or position in the program where the error occurred
Purpose:
- Allows programmers to understand and handle errors effectively.
- Can be used in
try-exceptblocks to access error details and respond appropriately.Example:
try: result = 10 / 0 except Exception as e: print("Error type:", type(e)) print("Error message:", e)Output:
Error type: <class 'ZeroDivisionError'> Error message: division by zeroKey Point for Exam:
- Its primary role is to provide detailed information about the error so that it can be handled or debugged.
- The exception object does not fix the error automatically, nor does it stop the program silently.
34. What happens to the remaining program statements when an exception occurs?
(A) They continue execution normally
(B) Execution jumps to the appropriate exception handler, abandoning the remaining statements
(C) Python ignores the exception and continues
(D) The interpreter asks the user to fix the code manually
Answer: (B) Execution jumps to the appropriate exception handler, abandoning the remaining statements
Explanation
Explanation:
When an exception is raised, Python stops executing the current block immediately and jumps to the appropriate exception handler (the
exceptblock) designed for that specific type of exception. Any statements after the point where the exception occurred in the same block are not executed. This ensures that the program does not crash abruptly and allows errors to be handled gracefully.For example:
try: print("Start") result = 10 / 0 # Exception occurs here print("This will not be printed") except ZeroDivisionError: print("Cannot divide by zero!") print("Program continues after exception handling")Output:
Start Cannot divide by zero! Program continues after exception handlingWhen an exception occurs, Python abandons the remaining statements in the block and executes the corresponding exception handler. This mechanism allows programs to handle errors gracefully without crashing.
35. What is the call stack in the context of exception handling?
(A) A list of all errors that occurred in the program
(B) A hierarchical list of methods/functions searched in reverse order to find a suitable exception handler
(C) The sequence of all input statements executed
(D) The storage area for program variables
Answer: (B) A hierarchical list of methods/functions searched in reverse order to find a suitable exception handler
Explanation
Call Stack in Exception Handling
Definition:
- The call stack is a hierarchy of active functions/methods at a specific point during program execution.
Purpose in Exception Handling:
- When an exception occurs, Python searches for an appropriate handler starting from the function where the exception was raised.
- If no handler is found, Python moves up the call stack (to the calling function) until a suitable handler is found or the top-level program is reached.
Mechanism:
- The call stack follows a Last-In, First-Out (LIFO) order.
- The most recently called function is checked first for an exception handler.
- Executing the found handler is called catching the exception.
Example:
def divide(a, b): return a / b def calculate(): try: result = divide(10, 0) except ZeroDivisionError: print("Cannot divide by zero!") calculate()Output:
Cannot divide by zero!Flow Explanation (Step-wise):
calculate()callsdivide(10, 0).ZeroDivisionErroroccurs individe(). Python checks for a handler individe()→ none found.- Python moves up to
calculate()→ finds the handler → exception is caught.Key Points for Exam:
- Call stack ensures organized and controlled exception handling.
- Python searches for exception handlers in reverse order of function calls, preventing abrupt program crashes.
36. What does catching an exception mean in Python?
(A) Ignoring the exception
(B) Finding and executing the suitable handler for the raised exception
(C) Rewriting the program automatically
(D) Stopping the program without any error message
Answer: (B) Finding and executing the suitable handler for the raised exception
Explanation
Explanation:
1. What is an Exception?
- An exception is an error that occurs during the execution of a program.
- Examples: dividing by zero (
ZeroDivisionError), accessing a file that doesn’t exist (FileNotFoundError), using an undefined variable (NameError).- When an exception occurs, Python raises it, which means it signals that an error has happened.
2. Catching an Exception
- Catching an exception means that Python detects the error and then executes a block of code specifically written to handle it.
- This is done using
tryandexceptblocks.- Instead of letting the program terminate abruptly (crash), the program can handle the error gracefully.
3. Why is it important?
- Keeps the main program logic separate from error-handling code.
- Makes the program robust, readable, and maintainable.
- Allows different types of errors to be handled differently, giving the programmer precise control over error handling.
4. How it works (Flow)
- Python executes code inside a
tryblock.- If no error occurs →
exceptblock is skipped.- If an error occurs → Python searches for a matching
exceptblock.- The matched handler executes → program continues without crashing.
5. Example:
# Example 1: Handling division by zero try: x = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") # Example 2: Handling file not found try: file = open("data.txt", "r") except FileNotFoundError: print("File not found!")Output:
Cannot divide by zero! File not found!
- Notice how each type of exception (
ZeroDivisionError,FileNotFoundError) is handled separately.6. Key Exam Points:
- Catching an exception = handling errors gracefully.
- Use
try–exceptblocks to prevent program crashes.- Specific exception types can have custom handlers → more precise error handling.
- Improves program robustness, readability, and maintainability.
37. What does it mean when an exception is said to be caught in Python?
(A) The program ignores the exception and continues execution
(B) The code designed to handle that particular exception is executed
(C) Python automatically corrects the error
(D) The program immediately terminates without any message
Answer: (B) The code designed to handle that particular exception is executed
Explanation
Explanation:
1. Definition of a Caught Exception
- When an exception occurs in Python, it is “caught” if the exception handler code written for that type of exception is executed.
- This ensures that the program can handle the error gracefully instead of terminating abruptly.
2. How it Works
- Python executes code inside a
tryblock.- If an error occurs that matches an
exceptblock, Python executes the handler code inside thatexceptblock.- The exception is now considered caught.
- If no matching handler exists, the program terminates with an error message.
3. Why Catching Exceptions is Useful
- Prevents the program from crashing unexpectedly.
- Allows the programmer to display meaningful error messages or take alternative actions.
- Keeps the main logic separate from error-handling code.
4. Example:
try: number = int(input("Enter a number: ")) result = 10 / number except ZeroDivisionError: print("Cannot divide by zero!") except ValueError: print("Invalid input! Please enter an integer.")Explanation of Example:
- If the user enters
0→ZeroDivisionErroris caught → prints"Cannot divide by zero!"- If the user enters
"abc"→ValueErroris caught → prints"Invalid input! Please enter an integer."- Program does not crash; appropriate messages are displayed.
5. Key Exam Points:
- Catching an exception = executing the specific handler code.
- Use
try-exceptblocks to handle expected runtime errors.- Helps in making programs robust, readable, and user-friendly.
38. What happens if the runtime system cannot find a suitable exception handler in the call stack?
(A) The program automatically corrects the error
(B) The exception is ignored, and execution continues
(C) The program terminates execution
(D) Python requests user input to fix the error
Answer: (C) The program terminates execution
Explanation
Explanation:
1. How Python Handles Exceptions
- When an exception occurs, Python searches for a matching exception handler in the current scope or method.
- If no handler is found there, it moves up the call stack (i.e., checks the functions/methods that called the current function) to find a suitable handler.
2. What Happens if No Handler is Found
- If Python cannot find a suitable handler anywhere in the call stack:
- The program terminates immediately.
- Python displays a traceback, showing the error type, message, and the sequence of function calls that led to the exception.
3. Why This Happens
- Allowing a program to continue after an unhandled exception could put it in an unpredictable state.
- Terminating execution ensures data integrity and signals clearly that an error occurred.
4. Example:
def divide(a, b): return a / b # may raise ZeroDivisionError def main(): result = divide(10, 0) # no try-except here main()Output:
Traceback (most recent call last): File "example.py", line 7, in <module> main() File "example.py", line 5, in main result = divide(10, 0) File "example.py", line 2, in divide return a / b ZeroDivisionError: division by zero
- Here, no handler exists, so Python terminates and prints the traceback.
5. Key Exam Points:
- If no suitable exception handler is found, Python terminates execution.
- Traceback helps in debugging by showing the call stack and error details.
- Always anticipate possible exceptions and handle them using try-except blocks to prevent abrupt termination.
39. What is the correct sequence of steps in Python’s exception handling process?
(A) Program terminates → Exception object created → Handler executed
(B) Exception object created → Exception raised → Runtime searches handler → Handler executed → Program continues or terminates
(C) Handler executed → Exception raised → Program terminates → Exception object created
(D) Exception ignored → Program continues execution
Answer: (B) Exception object created → Exception raised → Runtime searches handler → Handler executed → Program continues or terminates
Explanation
Explanation:
1. Step 1: Exception Object Creation
- When an error occurs in Python, the interpreter creates an exception object.
- This object contains information about the error, such as the type of exception and the error message.
2. Step 2: Exception Raised
- The exception object is raised (or thrown), signaling that an error has occurred.
- At this point, normal program execution is interrupted.
3. Step 3: Runtime Searches for Handler
- Python searches for a matching exception handler:
- First, in the current function or method.
- Then, in reverse order of the call stack (the functions that called the current function).
4. Step 4: Handler Executed (if found)
- If a suitable
exceptblock is found, it executes the handler code, which is also called catching the exception.- This prevents the program from terminating abruptly and allows it to handle the error gracefully.
5. Step 5: Program Continues or Terminates
- If the exception is handled, the program continues execution after the
exceptblock.- If no handler is found in the call stack, the program terminates, and Python displays a traceback showing the error details.
6. Example:
def divide(a, b): return a / b # may raise ZeroDivisionError try: result = divide(10, 0) except ZeroDivisionError: print("Cannot divide by zero!") print("Program continues execution.")Output:
Cannot divide by zero! Program continues execution.
- Stepwise sequence in this example:
ZeroDivisionErrorobject created- Exception raised
- Runtime searches for handler → finds
except ZeroDivisionError- Handler executed → prints message
- Program continues → prints
"Program continues execution."7. Key Exam Points:
- Always remember the sequence:
Exception object → Raised → Handler search → Handler executed → Continue/Terminate- Proper exception handling ensures robust and predictable programs.
40. What is meant by forwarding the exception in Python?
(A) Ignoring the exception entirely
(B) Searching for the exception handler in methods higher up in the call stack
(C) Catching the exception immediately in the same method
(D) Rewriting the program automatically
Answer: (B) Searching for the exception handler in methods higher up in the call stack
Explanation
Explanation:
1. Definition of Forwarding an Exception
- Forwarding an exception means that if Python cannot find a suitable handler in the current method, it passes the exception to the calling method.
- This process continues up the call stack until a handler is found or the program terminates.
2. Why Forwarding is Important
- It allows higher-level methods to handle exceptions that lower-level methods cannot.
- Ensures that exceptions are not lost, and the program can take appropriate action or terminate safely.
3. How it Works
- Exception occurs in a method/function.
- Python searches for a handler in the current method.
- If none is found → forwards the exception to the method that called the current one.
- The search continues up the call stack until a handler is found or the program terminates.
4. Example:
def divide(a, b): return a / b # may raise ZeroDivisionError def calculate(): result = divide(10, 0) # no try-except here try: calculate() # forwarding exception will be caught here except ZeroDivisionError: print("Exception caught in the calling method.")Output:
Exception caught in the calling method.
- Explanation:
divide()raisesZeroDivisionError- No handler in
divide()→ forwarded tocalculate()- No handler in
calculate()→ forwarded to outertry-except- Exception caught in outermost try block
5. Key Exam Points:
- Forwarding = searching for a handler higher in the call stack.
- Helps in centralized exception handling.
- If no handler exists anywhere in the stack → program terminates with traceback.
41. Why is the try block important in Python exception handling?
(A) It automatically fixes errors in the code
(B) It contains the code where an exception may occur, so exceptions can be caught
(C) It terminates the program if an error occurs
(D) It replaces the need for except blocks
Answer: (B) It contains the code where an exception may occur, so exceptions can be caught
Explanation
Explanation:
1. Purpose of the try Block
- The
tryblock is used to enclose the code that might raise an exception.- It allows Python to monitor for exceptions without stopping program execution abruptly.
2. How it Works
- Python executes statements inside the
tryblock.- If no exception occurs → the
exceptblock is skipped, and program continues normally.- If an exception occurs → control immediately transfers to the corresponding
exceptblock.- The exception is handled gracefully, preventing program crashes.
3. Why it is Important
- Separates normal program logic from error-handling code.
- Makes programs robust, readable, and maintainable.
- Allows specific handling of different types of exceptions using multiple
exceptblocks.4. Example:
try: number = int(input("Enter a number: ")) result = 10 / number except ZeroDivisionError: print("Cannot divide by zero!") except ValueError: print("Invalid input! Please enter an integer.") print("Program continues execution.")Output (if user enters 0):
Cannot divide by zero! Program continues execution.Output (if user enters “abc”):
Invalid input! Please enter an integer. Program continues execution.
- The
tryblock ensures exceptions are caught before the program crashes.5. Key Exam Points:
- Try block = code monitored for exceptions.
- Except block = code that handles the exception.
- Using
try-exceptensures program robustness and graceful error handling.
42. What is the purpose of a try block in Python?
(A) To catch all exceptions automatically without any except block
(B) To enclose code where an exception might occur so it can be handled
(C) To terminate the program if an error occurs
(D) To define a function
Answer: (B) To enclose code where an exception might occur so it can be handled
Explanation
Explanation:
1. Definition of a try Block
- A
tryblock is used to contain code that may raise an exception.- It allows Python to monitor for errors without stopping program execution abruptly.
2. How it Works
- Python executes the statements inside the
tryblock.- If no exception occurs → the
exceptblock is skipped, and program continues normally.- If an exception occurs → Python stops executing the remaining code inside the
tryblock.- Control is transferred to the matching
exceptblock, where the error can be handled.3. Why it is Important
- Separates normal program logic from error-handling code.
- Allows the program to handle errors gracefully instead of crashing.
- Enables handling different types of exceptions using multiple
exceptblocks.4. Example:
try: num = int(input("Enter a number: ")) result = 10 / num except ZeroDivisionError: print("Cannot divide by zero!") except ValueError: print("Invalid input! Please enter an integer.") print("Program continues execution.")Output (if user enters 0):
Cannot divide by zero! Program continues execution.Output (if user enters “abc”):
Invalid input! Please enter an integer. Program continues execution.
- The
tryblock ensures any potential exception is caught before the program crashes.5. Key Exam Points:
- Try block = monitored code for exceptions.
- Must be paired with except block(s) to handle errors.
- Ensures program robustness, readability, and graceful error handling.
43. What happens to the remaining statements in a try block if an exception occurs?
(A) They continue executing normally
(B) They are skipped, and control is transferred to the except block
(C) Python automatically corrects the error and continues
(D) The program terminates immediately
Answer: (B) They are skipped, and control is transferred to the except block
Explanation
Explanation:
1. Behavior of the try Block on Exception
- When an exception occurs inside a try block, Python immediately stops executing the remaining statements in that block.
- The rest of the code in the try block is skipped to prevent further errors.
2. Transfer of Control
- Control is then transferred to the corresponding except block that matches the exception type.
- The exception is handled gracefully, and the program can continue execution after the except block.
3. Why This Happens
- Prevents execution of statements that might depend on failed operations, avoiding further runtime errors.
- Ensures robustness and predictable program behavior.
4. Example:
try: print("Step 1") x = 10 / 0 # Raises ZeroDivisionError print("Step 2") # This line is skipped except ZeroDivisionError: print("Exception handled: Cannot divide by zero!") print("Program continues...")Output:
Step 1 Exception handled: Cannot divide by zero! Program continues...
- Notice
"Step 2"is skipped because the exception occurred before it.5. Key Exam Points:
- Any remaining statements after an exception in a try block are skipped.
- The corresponding except block executes to handle the error.
- Helps in maintaining program stability and avoiding further runtime errors.
44. Consider the following code snippet:
try:
quotient = numerator / denom
except ZeroDivisionError:
print("Denominator as ZERO not allowed")
What happens if denom is zero?
(A) The program prints the quotient
(B) The program crashes with a traceback
(C) The except block executes and prints “Denominator as ZERO not allowed”
(D) Python ignores the division and continues execution
Answer: (C) The except block executes and prints “Denominator as ZERO not allowed”
Explanation
Explanation:
1. What Happens in the Code
- The division
numerator / denomis inside a try block, which monitors for exceptions.- If
denom = 0, Python raises aZeroDivisionError.2. Control Flow on Exception
- Once the exception occurs:
- Python stops executing remaining statements in the try block (if any).
- Control is transferred to the matching except block.
- The except block executes the code:
print("Denominator as ZERO not allowed").- The program does not crash and continues after the except block.
3. Why This Happens
ZeroDivisionErroris a built-in exception for division by zero.- Using try-except allows graceful handling of runtime errors.
4. Example with Values:
numerator = 10 denom = 0 try: quotient = numerator / denom except ZeroDivisionError: print("Denominator as ZERO not allowed") print("Program continues...")Output:
Denominator as ZERO not allowed Program continues...
- The exception is caught, and program continues execution after the except block.
5. Key Exam Points:
- Division by zero raises ZeroDivisionError.
- Try-except block handles the exception gracefully.
- The program does not terminate abruptly when the exception is caught.
45. If no exception occurs in a try block, what happens to the except block?
(A) The except block is executed anyway
(B) The except block is skipped, and execution continues after the try…except block
(C) Python raises a new exception automatically
(D) The program stops execution
Answer: (B) The except block is skipped, and execution continues after the try…except block
Explanation
Explanation:
1. Behavior of the Except Block
- The except block only executes if an exception occurs in the associated try block.
- If no error occurs, Python skips the except block entirely.
2. Control Flow
- Python executes all statements inside the try block.
- No exception → except block is ignored.
- Execution continues with the next statement after the try…except block.
3. Why This Happens
- This ensures normal program flow when the code runs without errors.
- Prevents unnecessary execution of error-handling code.
4. Example:
try: result = 10 / 2 # No exception occurs except ZeroDivisionError: print("Cannot divide by zero!") print("Program continues execution.")Output:
Program continues execution.
- The except block is skipped because no exception occurred.
5. Key Exam Points:
- Except block executes only if an exception occurs in the try block.
- Normal program execution resumes after the try…except block when no error occurs.
- Using try-except does not affect normal program flow if there are no exceptions.
46. What is the purpose of the else block in a try…except…else structure in Python?
(A) It runs when an exception occurs in the try block
(B) It runs only if the try block executes without raising any exception
(C) It runs before the try block is executed
(D) It handles all uncaught exceptions automatically
Answer: (B) It runs only if the try block executes without raising any exception
Explanation
Explanation:
1. Meaning of theelseBlock
- The
elseblock in Python’s exception handling structure is optional.- It contains code that should run only when no exception occurs in the try block.
In short:
If the try block runs successfully (without errors), theelseblock executes.2. Syntax of
try…except…else:try: # Code that may raise an exception except ExceptionName: # Code to handle the exception else: # Code to run if no exception occurs3. Control Flow
- The code inside the try block executes.
- If an exception occurs → control goes to the except block.
- If no exception occurs → control goes to the else block.
- After the
elseblock executes, the program continues normally.4. Example:
try: num = int(input("Enter a number: ")) result = 10 / num except ZeroDivisionError: print("Error: Cannot divide by zero.") else: print("Division successful. Result =", result)Case 1:
If input =0Error: Cannot divide by zero.Case 2:
If input =5Division successful. Result = 2.0Note – The
elseblock runs only when no exception occurs.5. Key Exam Points
- The
elseblock is executed only if no exception occurs in the try block.- It helps in keeping the normal code separate from error-handling code.
- The use of
elseimproves readability and logical clarity of programs.
47. What is displayed when no exception occurs in the following code?
try:
numerator = 50
denom = int(input("Enter the denominator: "))
print(numerator/denom)
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO not allowed")
print("OUTSIDE try..except block")
(A) Denominator as ZERO not allowed
(B) Division performed successfully
(C) Division performed successfully
OUTSIDE try..except block
(D) Only INTEGERS should be entered
Answer: (C) Division performed successfully
OUTSIDE try..except block
Explanation
Explanation:
- When the user enters a non-zero integer, no exception is raised.
- The
tryblock executes completely, printing:"Division performed successfully".- After the
try…exceptblock finishes, the program continues normally and executes the next statement:"OUTSIDE try..except block".So, both messages appear sequentially.
Final Output Example (if input = 5):
10.0 Division performed successfully OUTSIDE try..except blockKey Concept:
If no exception occurs, the
exceptblock is skipped and the program flow continues with the next statements after thetry…exceptblock.
48. What happens if the user enters 0 as the denominator in the same program?
(A) The program prints the quotient
(B) The except block for ZeroDivisionError executes and prints the error message
(C) Python raises a ValueError automatically
(D) The program ignores the division and continues
Answer: (B) The except block for ZeroDivisionError executes and prints the error message
Explanation
Explanation:
- When the user enters 0 as the denominator, the statement
print(numerator / denom)causes Python to raise aZeroDivisionError, because division by zero is mathematically undefined.- The
except ZeroDivisionError:block catches this exception and executes its code:Denominator as ZERO not allowed- After handling the exception, Python skips the remaining statements in the
tryblock and continues with the next statement after the try…except block.Example Output (if input = 0):
Denominator as ZERO not allowed OUTSIDE try..except blockKey Concept:
The
ZeroDivisionErroris raised whenever a program tries to divide a number by zero.
Using a properexceptblock prevents program termination and allows smooth continuation of execution.
49. Which of the following is true about multiple except blocks?
(A) A try block can have only one except block
(B) Multiple except blocks can handle different exceptions for the same try block
(C) Except blocks are executed sequentially regardless of exception
(D) Multiple try blocks must be nested for multiple except blocks
Answer: (B) Multiple except blocks can handle different exceptions for the same try block
Explanation
Explanation:
- A single
tryblock can be followed by multipleexceptblocks, each designed to handle a different type of exception.- When an exception occurs, Python searches for the first matching
exceptblock and executes it.- All other
exceptblocks are skipped once a match is found.Example:
try: num1 = int(input("Enter numerator: ")) num2 = int(input("Enter denominator: ")) print(num1 / num2) except ZeroDivisionError: print("Error: Cannot divide by zero.") except ValueError: print("Error: Invalid input. Please enter integers only.")Case 1:
Input →num1 = 10,num2 = 0
→ Output →Error: Cannot divide by zero.Case 2:
Input →num1 = 10,num2 = 'a'
→ Output →Error: Invalid input. Please enter integers only.Key Concept:
- Multiple
exceptblocks = multiple exception types handled separately.- Only one matching
exceptblock executes per raised exception.
50. What exception will be raised if the user enters a non-integer value in the program?
denom = int(input("Enter the denominator: ")) (A) ZeroDivisionError
(B) TypeError
(C) ValueError
(D) NameError
Answer: (C) ValueError
Explanation
Explanation:
- Understanding the code:
input()always returns a string in Python.int()tries to convert the input string into an integer.- What happens with invalid input:
- If the user enters a non-integer string like
"abc"or a float like"3.5", Python cannot convert it to an integer.- This raises a ValueError:
denom = int("abc") # Raises ValueError- Why not other exceptions:
- ZeroDivisionError → only occurs when dividing by zero.
- TypeError → occurs when an operation is applied to an incompatible type, e.g.,
'5' + 3.- NameError → occurs when using a variable that is not defined.
- Handling the exception:
- You can prevent the program from crashing using an
except ValueErrorblock:try: denom = int(input("Enter the denominator: ")) except ValueError: print("Invalid input! Please enter an integer.")- Example runs:
- Input:
'abc'→ Output:Invalid input! Please enter an integer.- Input:
'5'→ Output:denom = 5(no exception occurs)Key Point:
ValueErroris raised whenever a function receives the correct type but an invalid value.- Always use
except ValueError:to safely handle input conversion errors.
51. Consider the following code snippet:
try:
numerator = 50
denom = int(input("Enter the denominator: "))
print(numerator/denom)
except ZeroDivisionError:
print("Denominator as ZERO not allowed")
except ValueError:
print("Only INTEGERS should be entered")
Which statement is correct if the user enters 0?
(A) ValueError block executes
(B) ZeroDivisionError block executes
(C) Both blocks execute
(D) No block executes
Answer: (B) ZeroDivisionError block executes
Explanation
Explanation:
- Step 1 — Input and try block
denom = int(input("Enter the denominator: ")) print(numerator / denom)
- User enters
0.int("0")successfully converts the input to integer → no ValueError occurs.- Next,
numerator / denom = 50 / 0→ Python raises ZeroDivisionError.
- Step 2 — Exception handling
- Python searches for an
exceptblock matching the raised exception.except ZeroDivisionError:matches → executes this block.except ValueError:does not match, so it is ignored.
- Step 3 — Output
Denominator as ZERO not allowedKey Concept:
- Python executes only the first matching except block for a raised exception.
- Other except blocks that do not match the exception type are skipped.
Quick Summary Table for this code:
Input Exception Raised Except Block Executed 0 ZeroDivisionError ZeroDivisionError block “abc” ValueError ValueError block 5 None No except block, normal execution This clearly demonstrates how multiple except blocks work in Python: only the matching one executes, and the rest are ignored..
52. What is the purpose of an except block without specifying an exception?
(A) To catch a specific exception
(B) To catch any exception that is not explicitly handled
(C) To terminate the program
(D) To ignore exceptions
Answer: (B) To catch any exception that is not explicitly handled
Explanation
Explanation:
- Generic
exceptblock
- An
except:block without an exception name is called a generic except block.- It can catch any exception that has not been handled by previous specific
exceptblocks.
- Why it’s useful
- It prevents the program from crashing unexpectedly when an unanticipated exception occurs.
- Acts as a catch-all safety net.
- Important rules
- Always place the generic
except:block at the end after all specificexceptblocks.- Otherwise, it would override specific exception handlers, preventing them from executing.
Example:
try: num = int(input("Enter a number: ")) result = 10 / num except ZeroDivisionError: print("Cannot divide by zero.") except ValueError: print("Invalid input! Enter an integer.") except: print("An unexpected error occurred.")Case 1: Input =
'abc'→ValueError→ Executesexcept ValueError
Case 2: Input =0→ZeroDivisionError→ Executesexcept ZeroDivisionError
Case 3: Some other unexpected exception occurs → Executes genericexcept:Key Concept:
- Use generic
except:for catching unexpected exceptions.- Ensures the program does not terminate abruptly.
- Always keep it after all specific except blocks to maintain proper exception handling order.
53. Consider the following code snippet:
try:
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = numerator/denom
except ValueError:
print("Only INTEGERS should be entered")
except:
print("OOPS...SOME EXCEPTION RAISED")
If the user enters 0 as the denominator, which output is displayed?
(A) Only INTEGERS should be entered
(B) OOPS…SOME EXCEPTION RAISED
(C) Division performed successfully
(D) ZeroDivisionError
Answer: (B) OOPS…SOME EXCEPTION RAISED
Explanation
Explanation:
- Step 1 — Input and try block
- User enters
0as the denominator.int("0")successfully converts the input → noValueError.- Next,
numerator / denom = 50 / 0→ Python raises ZeroDivisionError.
- Step 2 — Exception handling
- Python looks for a matching
exceptblock:
except ValueError:→ does not match, so skipped.except:→ generic catch-all block → executes.
- Step 3 — Output
OOPS...SOME EXCEPTION RAISEDKey Concept:
- A generic
except:block catches any exception not explicitly handled by previous specificexceptblocks.- This prevents the program from terminating abruptly when an unexpected exception occurs.
Quick Example Table for This Code:
Input Exception Raised Except Block Executed 0 ZeroDivisionError Generic except:block“abc” ValueError except ValueError:block5 None No exception, normal execution Takeaway:
- Use specific
exceptblocks for known exceptions.- Use a generic
except:at the end to handle unexpected errors safely.
54. Why should a generic except: block always be the last except block in a try..except structure?
(A) To handle specific exceptions before the generic catch
(B) To prevent syntax errors
(C) To improve performance
(D) To avoid using multiple except blocks
Answer: (A) To handle specific exceptions before the generic catch
Explanation
Explanation:
- Python executes except blocks sequentially:
- Python checks each
exceptblock in the order they appear.- It executes the first matching except block for the raised exception.
- Why place generic except last:
- A generic
except:block matches any exception.- If placed first, it will catch all exceptions, including those that specific except blocks are meant to handle.
- This prevents specific exception handlers from executing.
- Correct order:
try: # risky code except ZeroDivisionError: print("Cannot divide by zero.") # specific handler except ValueError: print("Invalid input!") # specific handler except: print("Some unexpected error occurred") # generic catchKey Concept:
- Specific exceptions first → Generic exception last.
- Ensures proper handling of known exceptions while still catching unexpected ones.
Takeaway:
- Always place
except:at the end to avoid overriding specific exception handlers.
55. What is the role of the else clause in a try..except structure?
(A) Executes only when an exception occurs
(B) Executes only when no exception occurs in the try block
(C) Terminates the program if an exception occurs
(D) Re-raises the exception
Answer: (B) Executes only when no exception occurs in the try block
Explanation
Explanation:
- Purpose of the else clause:
- The
elseclause is optional in Python’s exception-handling structure.- It contains code that should execute only when the try block succeeds without raising any exception.
- Why use it:
- Helps keep normal execution code separate from exception-handling code, improving readability and logical clarity.
- Syntax Example:
try: num = int(input("Enter a number: ")) result = 10 / num except ZeroDivisionError: print("Cannot divide by zero.") except ValueError: print("Invalid input! Enter an integer.") else: print("Division successful. Result =", result)Example Runs:
- Input = 5:
Output:Division successful. Result = 2.0
- Input = 0:
Output:Cannot divide by zero.
- Input = “abc”:
Output:Invalid input! Enter an integer.Observation:
elseruns only when no exception occurs.- If any exception occurs, the
elseblock is skipped.Key Concept:
elseis used for code that should run only under normal conditions.- It separates normal execution from error handling, enhancing clarity and maintainability.
56. Which of the following is true about exception handling in Python?
(A) The try block is optional
(B) Only one except block is allowed per try block
(C) Multiple except blocks, generic except, and else can be used for a single try block
(D) The else block executes even if an exception occurs
Answer: (C) Multiple except blocks, generic except, and else can be used for a single try block
Explanation
Explanation:
- Multiple except blocks:
- A single
tryblock can have multiple except blocks to handle different types of exceptions separately.
- Generic except block:
- A generic
except:block can catch any exception not handled by specific except blocks.- It should be placed after all specific except blocks to avoid overriding them.
- Optional else block:
- The
elseblock executes only if no exceptions occur in the try block.- It keeps normal execution separate from error-handling logic.
Example:
try: num1 = int(input("Enter numerator: ")) num2 = int(input("Enter denominator: ")) result = num1 / num2 except ZeroDivisionError: print("Cannot divide by zero.") except ValueError: print("Invalid input! Enter an integer.") except: print("Some unexpected error occurred.") else: print("Division successful. Result =", result)Observations:
- Handles multiple specific exceptions.
- Catches unhandled exceptions with generic
except:.- Runs else block only if no exception occurs.
Key Concept:
Python provides flexible and structured exception handling:
- Multiple specific handlers
- Generic catch-all handler
- Optional
elsefor normal executionThis makes programs robust and easier to maintain.
57. What is the purpose of the else clause in a try..except block?
(A) Executes only if an exception is raised in the try block
(B) Executes only if no exception occurs in the try block
(C) Re-raises an exception
(D) Terminates the program
Answer: (B) Executes only if no exception occurs in the try block
Explanation
Explanation:
- Purpose of the else clause:
- The
elseclause is optional and runs only if the try block executes successfully without raising any exception.
- Why it is useful:
- It separates normal execution code from exception-handling code, improving readability and maintainability.
- Behavior:
- If an exception occurs → the corresponding
exceptblock executes, and theelseblock is skipped.- If no exception occurs → the
elseblock executes after thetryblock.Example:
try: num = int(input("Enter a number: ")) result = 10 / num except ZeroDivisionError: print("Cannot divide by zero.") except ValueError: print("Invalid input! Enter an integer.") else: print("Division successful. Result =", result)Cases:
- Input =
5→ Output:"Division successful. Result = 2.0"→elseexecutes- Input =
0→ Output:"Cannot divide by zero."→elseskipped- Input =
"abc"→ Output:"Invalid input! Enter an integer."→elseskippedKey Concept:
elseruns only when the try block succeeds.- It keeps normal execution separate from error-handling logic.
58. Consider the following code:
try:
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = numerator / denom
except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
except ValueError:
print("Only INTEGERS should be entered")
else:
print("The result of division operation is", quotient)
If the user enters 5 as the denominator, which output is displayed?
(A) Denominator as ZERO is not allowed
(B) Only INTEGERS should be entered
(C) The result of division operation is 10.0
(D) None
Answer: (C) The result of division operation is 10.0
Explanation
Explanation:
- What happens step-by-step:
numerator = 50denom = 5→ successfully converted to integerquotient = 50 / 5→10.0- No exception is raised.
- Control flow:
- Since no exception occurs, both
exceptblocks are skipped.- The program moves to the else block, which executes and displays:
The result of division operation is 10.0- Why the else block runs:
- The
elseclause in atry..exceptstructure executes only when the try block runs successfully without any exceptions.Key Concept:
- ZeroDivisionError → occurs only when denominator is 0.
- ValueError → occurs only when a non-integer input is entered.
- Else block → runs only when no exceptions occur.
Final Output:
The result of division operation is 10.0
59. What is the main advantage of using the finally clause in Python exception handling?
(A) Executes only when an exception occurs
(B) Executes only when no exception occurs
(C) Executes regardless of whether an exception occurs or not
(D) Executes only for built-in exceptions
Answer: (C) Executes regardless of whether an exception occurs or not
Explanation
Explanation:
- Purpose of the finally clause:
- The
finallyclause is used to define code that must always execute, whether an exception occurs or not.- It is typically used for cleanup operations like closing files, releasing memory, or disconnecting from a database.
- Execution behavior:
- If no exception occurs →
finallyexecutes after thetry(andelse, if present).- If an exception occurs and is caught →
finallystill executes after theexceptblock.- If an exception occurs and is not caught, the
finallyblock executes before the program terminates.Example:
try: file = open("data.txt", "r") data = file.read() except FileNotFoundError: print("File not found.") finally: print("Closing file (if open).") try: file.close() except: passOutput cases:
- If file exists → file is read, then “Closing file (if open).” is printed.
- If file doesn’t exist → “File not found.” and then “Closing file (if open).”
Key Concept:
- The
finallyclause guarantees the execution of important cleanup code.- Ensures reliability and resource safety, even in case of runtime errors.
Summary:
Thefinallyblock in Python always executes, making it essential for cleanup, resource management, and program stability.
60. In a try..except..else..finally structure, in what order are the blocks executed when no exception occurs?
(A) try → except → else → finally
(B) try → else → finally
(C) try → finally → else
(D) try → except → finally
Answer: (B) try → else → finally
Explanation
Explanation:
- Execution Flow (when no exception occurs):
- Step 1: The
tryblock executes first.- Step 2: Since no exception occurs, all
exceptblocks are skipped.- Step 3: The optional
elseblock executes next.- Step 4: Finally, the
finallyblock executes, regardless of the outcome.Example:
try: num = int(input("Enter a number: ")) result = 10 / num except ZeroDivisionError: print("Cannot divide by zero.") else: print("Division successful. Result =", result) finally: print("Program execution completed.")Case: Input = 5
Output:
Division successful. Result = 2.0 Program execution completed.Flow:
try → else → finallyKey Concept:
No Exception try → else → finally Exception Caught try → except → finally Exception Not Caught try → finally (before program ends with error) Summary:
tryruns first.- If no error →
elseruns.- Finally →
finallyalways runs last.This sequence ensures clear separation between normal execution, error handling, and cleanup operations.
61. Where should the finally clause be placed in a try..except structure?
(A) Before the try block
(B) After the try block but before except blocks
(C) After all except blocks and optional else block
(D) Anywhere in the program
Answer: (C) After all except blocks and optional else block
Explanation
Explanation:
- Position of the finally clause:
- The
finallyblock must always be placed at the end of atry..exceptstructure.- It comes after all
exceptblocks and the optionalelseblock (if present).- This ensures that the cleanup code in
finallyruns after all normal or error-handling code has finished.- Purpose:
- The
finallyclause contains code that must always execute, such as closing files, releasing resources, or printing completion messages.Correct Syntax Example:
try: # Code that may raise an exception except SomeException: # Handle the exception else: # Executes only if no exception occurs finally: # Executes always, regardless of exceptionExample in Practice:
try: num = int(input("Enter a number: ")) result = 10 / num except ZeroDivisionError: print("Cannot divide by zero.") else: print("Division successful. Result =", result) finally: print("Program execution completed.")Case 1: Input = 5
Output:Division successful. Result = 2.0 Program execution completed.Case 2: Input = 0
Output:Cannot divide by zero. Program execution completed.Key Concept:
- The
finallyblock must be the last clause in the exception-handling sequence.- It ensures proper cleanup and resource release regardless of what happens in the try or except blocks.
Summary:
The correct placement of thefinallyblock — after all except and else clauses — guarantees that it executes last, maintaining clean and predictable program flow.
62. What output will the following program produce if the user enters 0 as the denominator?
try:
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = numerator / denom
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
else:
print("The result of division operation is", quotient)
finally:
print("OVER AND OUT")
(A) Division performed successfully
(B) Denominator as ZERO is not allowed
(C) OVER AND OUT
(D) Both B and C
Answer: (D) Both B and C
Explanation
Explanation:
- Step-by-step execution:
- The user enters 0.
- Python attempts to execute
quotient = numerator / denom, i.e.,50 / 0.- This raises a ZeroDivisionError.
- Control flow:
- The
except ZeroDivisionErrorblock executes, printing:
"Denominator as ZERO is not allowed"- Since an exception occurred, the
elseblock is skipped.- The
finallyblock always executes, printing:
"OVER AND OUT"- Final Output:
Denominator as ZERO is not allowed OVER AND OUTKey Points to Remember:
elseblock executes only if no exception occurs.finallyblock executes always, regardless of exceptions.- When an exception occurs, control moves directly to the matching
exceptblock.Summary:
When the denominator is 0 →
- The program prints the error message from
except.- The cleanup message from
finallyis printed.
Hence, the correct answer is (D) Both B and C.
63. If no exception occurs in a try..except..else..finally structure, in what order will the blocks execute?
(A) try → except → else → finally
(B) try → else → finally
(C) try → finally → else
(D) try → except → finally
Answer: (B) try → else → finally
Explanation
Explanation:
- Execution Flow (No Exception Occurs):
- Step 1: The code inside the
tryblock executes first.
If no exception occurs, Python moves to the next step.- Step 2: The
elseblock executes (optional).
This block runs only when the try block executes successfully without any errors.- Step 3: The
finallyblock executes.
This block always executes, regardless of whether an exception occurred or not.- Control Flow Summary:
try → else → finally- Why This Order?
try: contains main operation (may raise exceptions).else: runs only if try succeeded (used for post-success actions).finally: runs always (used for cleanup, closing files, etc.).Example Code:
try: print("In try block") except ZeroDivisionError: print("In except block") else: print("In else block") finally: print("In finally block")Output:
In try block In else block In finally blockKey Point to Remember:
elseexecutes only if no exception occurs.finallyexecutes always, whether an exception occurs or not.Summary:
When no exception occurs, Python executes blocks in this order →
try → else → finally
Hence, the correct answer is (B).
64. Which of the following statements about the finally clause is true?
(A) Finally executes only when an exception occurs
(B) Finally executes only when no exception occurs
(C) Finally executes regardless of whether an exception occurs or not
(D) Finally can be placed before the try block
Answer: (C) Finally executes regardless of whether an exception occurs or not
Explanation
Explanation:
- Purpose of the
finallyBlock:
- The
finallyclause is used to define cleanup code that must run no matter what happens—
whether the code in thetryblock succeeds, fails, or even raises an exception.- It is especially useful for releasing resources (like files, database connections, or memory).
- Execution Behavior:
- If no exception occurs →
finallyexecutes after try (and else, if present).- If an exception occurs →
finallyexecutes after the except block.- If the program exits or returns from inside try or except →
finallystill executes before exiting.Example Code 1 (No Exception):
try: print("In try block") except: print("In except block") finally: print("In finally block")Output:
In try block In finally blockExample Code 2 (With Exception):
try: print(10 / 0) except ZeroDivisionError: print("Exception caught") finally: print("Finally always executes")Output:
Exception caught Finally always executesKey Points to Remember:
finallyblock always runs (even ifreturn,break, orcontinueappears in try/except).- Used mainly for resource cleanup (closing files, freeing memory, etc.).
- It cannot appear before the
tryblock. It must be placed after all except/else blocks.Summary:
Thefinallyblock always executes, regardless of whether an exception occurs or not, ensuring essential cleanup tasks are completed.
65. What happens if an exception occurs in the try block, but there is no matching except block?
(A) The program terminates immediately
(B) The finally block is executed before the program terminates
(C) The exception is ignored
(D) Only the else block executes
Answer: (B) The finally block is executed before the program terminates
Explanation
Explanation:
- When an exception occurs:
- Python searches for a matching
exceptblock that can handle the exception.- If no matching except block is found, Python prepares to terminate the program by re-raising the exception.
- Role of the
finallyBlock:
- Before the program terminates, Python always executes the
finallyblock (if it exists).- This ensures that cleanup code (like closing files, releasing resources, etc.) runs even if the exception is unhandled.
- Program Termination:
- After the
finallyblock finishes execution, Python terminates the program and displays the error traceback message indicating the unhandled exception.Example Code:
try: print("In try block") x = 10 / 0 finally: print("In finally block")Output:
In try block In finally block Traceback (most recent call last): File "example.py", line 3, in <module> x = 10 / 0 ZeroDivisionError: division by zeroExplanation of Output:
- The
ZeroDivisionErrorexception occurs.- There is no except block to handle it.
- Before terminating, Python executes the
finallyblock (In finally block).- After that, the program ends with a traceback showing the error.
Key Points to Remember:
- The
finallyblock always executes, even when there’s no matching except.- The program still terminates afterward because the exception remains unhandled.
- The exception is not ignored, and the else block never executes if an exception occurs.
Summary:
If an exception occurs and no suitableexceptblock is found, Python executes thefinallyblock first, then terminates the program by re-raising the exception.
66. In a try..except..else..finally structure, which block is optional?
(A) try
(B) except
(C) else
(D) finally
Answer: (C) else
Explanation
Explanation:
tryblock → Mandatory
- It contains the code that may raise exceptions.
- You cannot have exception handling without a
tryblock.exceptblock → Mandatory (at least one required)
- It handles the exception raised in the
tryblock.- You can have multiple
exceptblocks for different exception types.- A generic
except:can also be used if you want to handle all exceptions.elseblock → Optional
- Executes only if no exception occurs in the
tryblock.- Useful for code that should run only after a successful
tryblock.- Helps separate “normal logic” from “error-handling logic”.
finallyblock → Optional but recommended
- Executes regardless of whether an exception occurs or not.
- Commonly used for cleanup operations like closing files, releasing memory, or disconnecting from databases.
Example Code:
try: x = int(input("Enter a number: ")) print(10 / x) except ZeroDivisionError: print("Cannot divide by zero!") else: print("Division successful!") finally: print("Execution completed.")Case 1: Input = 5
2.0 Division successful! Execution completed.Case 2: Input = 0
Cannot divide by zero! Execution completed.Explanation of Output:
- When no exception →
try → else → finally- When exception occurs →
try → except → finally- The
elseblock runs only whentryexecutes successfully without any exception.Key Takeaways:
elseis the only optional block that executes only if no exception occurs.finallyis optional but strongly recommended for cleanup tasks.tryandexceptare mandatory; Python will raise a syntax error if they are missing.Summary:
In Python’stry..except..else..finallystructure:
try→ mandatoryexcept→ at least one mandatoryelse→ optionalfinally→ optional but commonly used
67. What will happen if a non-numeric input is entered for the denominator in the following code?
try:
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = numerator / denom
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
else:
print("The result of division operation is", quotient)
finally:
print("OVER AND OUT")
(A) The program executes without any error.
(B) Only the finally block executes and the exception continues to be raised.
(C) The except block executes and finally block is skipped.
(D) The else block executes before finally.
Answer: (B) Only the finally block executes and the exception continues to be raised.
Explanation
Explanation:
- What happens when a non-numeric value is entered?
- The statement
denom = int(input("Enter the denominator: "))tries to convert user input to an integer.- If the input is non-numeric (e.g., “abc”), Python cannot convert it to an integer →
This raises aValueErrorexception.- Is the ValueError handled in the code?
- The code only has an
except ZeroDivisionError:block.- Since there is no except block for ValueError, the program does not handle this exception.
- What executes next?
Hence, it prints:
- Before the program terminates, the finally block executes.
- This block always runs — no matter what happens (exception, no exception, or even a return statement).
OVER AND OUT- What happens after the finally block?
- After executing
finally, the unhandled ValueError is re-raised automatically by Python.- The program then stops with a traceback (error message) because there’s no handler for that exception.
Step-by-Step Flow (when input = “abc”):
1 denom = int("abc")Raises ValueError2 except ZeroDivisionErrorSkipped (doesn’t match) 3 elseSkipped (exception occurred) 4 finallyExecutes → prints "OVER AND OUT"5 Exception Re-raised → Program terminates with traceback Output on screen:
OVER AND OUT Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: 'abc'Key Takeaways:
- The finally block always executes, regardless of whether an exception occurs or not.
- If an exception is not caught by any
exceptblock, it is re-raised afterfinally.- The else block executes only if no exception occurs.
- Best practice: Always include handlers for all possible exceptions (e.g.,
ValueError,ZeroDivisionError) when dealing with user input.Summary:
When a non-numeric value is entered:
- A
ValueErroroccurs.- No matching
exceptblock is found.finallyexecutes → prints"OVER AND OUT".- Then the unhandled exception terminates the program.
68. In a try..except..else..finally structure, what is the effect of the finally block on unhandled exceptions?
(A) Finally block suppresses the exception.
(B) Finally block executes and terminates the program.
(C) Finally block executes and the exception is re-raised.
(D) Finally block executes only if there is an except block.
Answer: (C) Finally block executes and the exception is re-raised.
Explanation
Explanation:
- Purpose of the
finallyblock:
- The
finallyblock is used to guarantee execution of important code, such as cleanup operations, regardless of whether an exception occurs.- It does not suppress or terminate exceptions.
- Behavior with unhandled exceptions:
- If an exception occurs in the
tryblock and there is no matchingexceptblock, Python does the following:
- Executes the
finallyblock first.- After
finallyexecutes, the unhandled exception is automatically re-raised, causing the program to terminate with a traceback.- Why this matters:
- This behavior ensures that cleanup operations (like closing files, releasing resources, etc.) always occur, even when an error is not handled.
- Programmers can safely rely on
finallyto maintain program stability and resource safety.Example:
try: x = int(input("Enter a number: ")) result = 10 / x finally: print("This always executes") # No except blockCase 1: Input = 0
Output:
This always executes Traceback (most recent call last): File "example.py", line 3, in <module> result = 10 / 0 ZeroDivisionError: division by zeroExplanation:
finallyprints"This always executes".- Since there is no
exceptblock,ZeroDivisionErroris re-raised afterfinally.Key Points:
finallyalways executes, no matter what.- Unhandled exceptions are not suppressed by
finally.- After
finally, the unhandled exception is re-raised, terminating the program if not caught at a higher level.Summary:
Thefinallyblock ensures cleanup code runs while allowing unhandled exceptions to propagate.
69. Which of the following statements about exception handling in Python is correct?
(A) Try block executes only if an exception occurs.
(B) Except block executes even if no exception occurs.
(C) Else block executes only if no exception occurs.
(D) Finally block executes only if an exception occurs.
Answer: (C) Else block executes only if no exception occurs.
Explanation
Explanation:
- Try block:
- The code inside the
tryblock always executes first, regardless of whether an exception occurs later.- It is used to enclose code that may potentially raise exceptions.
- Except block:
- Executes only if a matching exception occurs in the
tryblock.- If no exception occurs, the
exceptblock is skipped.- Else block:
- Executes only if the
tryblock completes successfully without raising any exceptions.- Useful for separating normal execution logic from error-handling logic.
- Finally block:
- Executes always, whether an exception occurs or not.
- Commonly used for cleanup actions (like closing files or releasing resources).
Example Code:
try: x = int(input("Enter a number: ")) result = 10 / x except ZeroDivisionError: print("Cannot divide by zero!") else: print("Division successful:", result) finally: print("Execution finished.")Case 1: Input = 2
Output:Division successful: 5.0 Execution finished.Case 2: Input = 0
Output:Cannot divide by zero! Execution finished.Key Points:
Block Executes When? try Always first except Only if a matching exception occurs else Only if no exception occurs finally Always executes Summary:
- The else block executes only when the try block succeeds without exceptions, making.
70. Which statement summarizes the correct flow of execution in a try..except..else..finally construct?
(A) Try → Except → Else → Finally → Next statements
(B) Try → Except (if matched) → Else (if no exception) → Finally → Next statements
(C) Try → Else → Except → Finally
(D) Try → Finally → Except → Else
Answer: (B) Try → Except (if matched) → Else (if no exception) → Finally → Next statements
Explanation
Explanation:
- Execution Flow:
Try Block:
The code inside thetryblock is executed first.
This block contains the statements that might raise exceptions.
Except Block:
If an exception occurs in thetryblock and matches the type specified in anexceptblock, thatexceptblock executes.
If no exception occurs, theexceptblock is skipped entirely.
Else Block:
Theelseblock executes only if thetryblock runs successfully without raising any exceptions.
This is useful for code that should run only when no errors occur.
Finally Block:
Thefinallyblock executes always, regardless of whether an exception occurred or not.
It is commonly used for cleanup tasks, like closing files, releasing resources, or other mandatory operations.
Next Statements:
After thefinallyblock executes, the program continues with the statements following thetry..except..else..finallyconstruct.- Why Option B is Correct:
- It correctly reflects conditional execution of
exceptandelse.- It ensures
finallyruns always, and the program continues with the next statements after the construct.- Incorrect Options:
- (A) → Incorrect because
exceptmay not always run;elsedoes not execute afterexcept.- (C) → Incorrect order;
elsecannot execute beforeexcept.- (D) → Incorrect;
finallycannot execute beforeexceptorelse.Example Code Demonstrating Flow:
try: x = int(input("Enter a number: ")) result = 10 / x except ZeroDivisionError: print("Cannot divide by zero!") else: print("Division successful:", result) finally: print("This always executes") print("Program continues...")Case 1: Input = 2
Division successful: 5.0 This always executes Program continues...Case 2: Input = 0
Cannot divide by zero! This always executes Program continues...Key Points:
try→ always firstexcept→ executes only if exception occurselse→ executes only if no exception occursfinally→ executes always- Execution continues with the next statements after
finallySummary:
The correct flow of execution in a
try..except..else..finallyconstruct is:Try → Except (if matched) → Else (if no exception) → Finally → Next statement
71. Why is it recommended to include a finally block when working with resources like files or network connections?
(A) To ignore exceptions raised in try block.
(B) To ensure the resource is released/closed even if an exception occurs.
(C) To skip the else block.
(D) To automatically terminate the program after try block.
Answer: (B) To ensure the resource is released/closed even if an exception occurs.
Explanation
Explanation:
- Purpose of the
finallyblock:
- The
finallyblock is designed to execute always, regardless of whether an exception occurs in thetryblock.- This makes it perfect for tasks that must be performed no matter what, such as releasing resources.
- Working with resources:
- When a program opens a file, network connection, or database connection, it is crucial to close or release the resource after use.
- If the program raises an exception before releasing the resource, it could lead to resource leaks or locked resources.
- How
finallyhelps:
- By placing cleanup code inside
finally, you guarantee that the resource is released even if an exception occurs in thetryblock.Example Code:
try: file = open("example.txt", "r") data = file.read() print(data) except FileNotFoundError: print("File not found!") finally: file.close() print("File closed successfully")Explanation of Output:
- If the file exists →
tryexecutes → data is printed →finallyexecutes → file is closed.- If the file does not exist →
exceptexecutes → prints “File not found!” →finallyexecutes → ensures file is closed.Key Points:
- Ensures resource cleanup (files, network connections, database connections, etc.).
- Prevents resource leaks even when exceptions occur.
- Does not ignore exceptions; it simply guarantees execution of cleanup code.
Summary:
Thefinallyblock is essential for managing resources safely. It ensures that resources like files or network connections are always released, even in the presence of exceptions.
72. What happens when a syntax error is encountered in a Python program?
(A) Python ignores the error and continues execution.
(B) Python displays the error name and description, and program execution starts only after the error is corrected.
(C) Python automatically corrects the syntax error.
(D) The program execution is aborted without any message.
Answer: (B) Python displays the error name and description, and program execution starts only after the error is corrected.
Explanation
Explanation:
- What is a Syntax Error?
- A syntax error occurs when the code violates the rules of Python grammar.
- Examples include missing colons, unmatched parentheses, or incorrect indentation.
- Python’s Response:
- When a syntax error is detected, Python immediately stops program execution.
- It displays the error name (
SyntaxError) and a brief description of the problem.- Execution cannot proceed until the error is corrected.
- Key Points:
- Syntax errors are not runtime errors; they prevent the program from starting.
- Unlike exceptions, syntax errors cannot be caught using
try..exceptbecause the program never executes beyond the point of the error.Example Code with Syntax Error:
# Missing colon after if statement x = 10 if x > 5 print("x is greater than 5")Output:
File "example.py", line 3 if x > 5 ^ SyntaxError: expected ':'
- Python points out where the error occurred and gives a description (
expected ':').- The program does not run until the error is fixed.
Summary:
- Syntax errors stop program execution immediately.
- Python displays the error name and description.
- Program execution can continue only after correcting the error.
73. Which of the following statements is true about exceptions in Python?
(A) Exceptions can only be caused by syntax errors.
(B) An exception is a Python object representing an error that occurs during program execution.
(C) Exceptions terminate the program automatically without any handling mechanism.
(D) Only built-in exceptions exist; user cannot define exceptions.
Answer: (B) An exception is a Python object representing an error that occurs during program execution.
Explanation
Explanation:
- Definition of Exception
- An exception in Python is a runtime object that indicates an error occurred during program execution.
- Exceptions are not syntax errors; they occur while the program is running.
- Examples of Exceptions
ZeroDivisionError→ dividing a number by zeroFileNotFoundError→ trying to open a file that doesn’t existNameError→ using an undefined variable
- Exception Objects
- Every exception in Python is an object.
- It contains information about the type of error and an optional error message.
- Handling Exceptions
- Python provides
try..exceptblocks to catch and handle exceptions, preventing program crashes.- Both built-in and user-defined exceptions can be handled.
Example:
try: x = int(input("Enter a number: ")) result = 10 / x except ZeroDivisionError: print("Cannot divide by zero!") except ValueError: print("Invalid input! Please enter an integer.") else: print("Result:", result)
- If the user enters
0,ZeroDivisionErroris caught.- If the user enters a non-integer,
ValueErroris caught.- If the user enters a valid number, the
elseblock executes.Summary:
- Exceptions are Python objects representing runtime errors.
- They can be built-in or user-defined.
- Using
try..exceptensures robust and maintainable code.
74. Which of the following are commonly occurring built-in exceptions in Python?
(A) SyntaxError, ValueError, ZeroDivisionError
(B) IOError, KeyboardInterrupt, ImportError
(C) EOFError, NameError, TypeError, IndentationError
(D) All of the above
Answer: (D) All of the above
Explanation
Explanation:
- Built-in Exceptions in Python
- Python provides a large number of built-in exception classes to indicate different types of runtime errors.
- These exceptions are predefined Python objects and are automatically raised by the interpreter when an error occurs.
- Common Examples
- SyntaxError → invalid Python syntax
- ValueError → invalid value type (e.g.,
int("abc"))- ZeroDivisionError → division by zero
- IOError / FileNotFoundError → file operations fail
- KeyboardInterrupt → user interrupts program (Ctrl+C)
- ImportError → failed import of module or package
- EOFError → end-of-file reached unexpectedly
- NameError → variable not defined
- TypeError → operation on incompatible types
- IndentationError → incorrect indentation
- OverflowError → numeric overflow
- Purpose of Built-in Exceptions
- Each exception informs the programmer about the type of error that occurred.
- They can be caught using
try..exceptblocks, allowing the program to handle errors gracefully and continue execution.Example:
try: x = int(input("Enter a number: ")) result = 10 / x except ZeroDivisionError: print("Cannot divide by zero!") except ValueError: print("Invalid input! Enter an integer.")
- The above program can handle multiple built-in exceptions like
ValueErrorandZeroDivisionError.Summary:
- Python has many built-in exceptions for common runtime errors.
- These exceptions are objects that can be caught and handled to make programs more robust.
- All examples in options A, B, and C are valid built-in exceptions, so the correct answer is D.
75. What is the purpose of exception handlers in Python?
(A) To prevent the program from terminating abruptly by handling errors.
(B) To detect syntax errors before execution.
(C) To automatically optimize program performance.
(D) To define variables in the program.
Answer: (A) To prevent the program from terminating abruptly by handling errors.
Explanation
Explanation:
- Definition of Exception Handlers
- An exception handler is a block of code (inside an
exceptclause) designed to handle specific runtime errors (exceptions).- Exception handlers catch errors and allow the program to continue execution safely.
- Purpose
- Prevent abrupt termination of the program.
- Provide a way to respond to errors gracefully, such as printing an error message or taking corrective action.
- Improve program robustness, reliability, and maintainability.
- How Exception Handlers Work
- The
tryblock contains code that may raise exceptions.- The
exceptblock is the exception handler that executes when a matching exception occurs.Example:
try: x = int(input("Enter a number: ")) result = 10 / x except ZeroDivisionError: print("Cannot divide by zero!") # Exception handler except ValueError: print("Invalid input! Please enter an integer.") # Exception handler else: print("Result:", result)
- If an exception occurs (like dividing by zero or invalid input), the corresponding exception handler executes.
- The program does not crash; it continues execution after handling the error.
Summary:
- Exception handlers catch runtime errors and prevent the program from terminating unexpectedly.
- They allow graceful error handling and improve the program’s robustness.
76. Which statements are used in Python to raise exceptions intentionally?
(A) try and except
(B) raise and assert
(C) else and finally
(D) input and print
Answer: (B) raise and assert
Explanation
Explanation:
- Raising Exceptions Manually
- Python allows programmers to raise exceptions intentionally using the
raisestatement.- This is useful when you want to signal an error condition in your code.
Example:
x = -5 if x < 0: raise ValueError("Negative value not allowed")
- Output:
ValueError: Negative value not allowed- The program stops unless this exception is handled with a
try..exceptblock.
- Using
assertStatement
- The
assertstatement is used to check a condition.- If the condition is False, Python raises an AssertionError.
- This is commonly used for debugging and validating assumptions.
Example:
x = 10 assert x > 0, "x must be positive"
- If
xis not greater than 0,AssertionErroris raised with the provided message.
- Effect of Raising Exceptions
- Raising an exception interrupts normal program flow.
- Control is transferred to the appropriate exception handler if one exists; otherwise, the program terminates with an error.
Summary:
raise→ manually raises any specified exception.assert→ raises anAssertionErrorif a condition is false.- Both are used to intentionally trigger exceptions for error handling or debugging purposes.
77. What is the role of the finally block in exception handling?
(A) Executes only if an exception occurs in the try block.
(B) Executes only if no exception occurs in the try block.
(C) Executes always, regardless of whether an exception occurred or not.
(D) Suppresses all exceptions in the program.
Answer: (C) Executes always, regardless of whether an exception occurred or not.
Explanation
Explanation:
- Definition of Finally Block
- The finally block is an optional part of a
try..exceptstructure.- It contains code that must be executed no matter what, whether an exception occurs or not.
- Purpose of Finally
- Commonly used for cleanup activities, such as:
- Closing files
- Releasing network or database resources
- Releasing locks or other resources
- Execution Flow
tryblock executes first.- If an exception occurs: the matching
exceptblock executes.- Regardless of whether
exceptexecutes or not, thefinallyblock always executes.- If the exception is unhandled, it is re-raised after finally executes.
Example:
try: x = int(input("Enter a number: ")) result = 10 / x except ZeroDivisionError: print("Cannot divide by zero!") finally: print("This will always execute")
- Input =
0→ except executes, then finally executes- Input =
5→ no exception, try executes, then finally executesOutput when input = 0:
Cannot divide by zero! This will always executeOutput when input = 5:
This will always executeSummary:
- Finally block executes always, regardless of exceptions.
- It ensures essential cleanup tasks are performed.
- Exceptions are not suppressed; they are re-raised after finally if unhandled.
78. When is an exception said to be caught in Python?
(A) When the try block executes successfully without error.
(B) When code in the except block executes for a raised exception.
(C) When finally block is executed.
(D) When the program terminates abruptly.
Answer: (B) When code in the except block executes for a raised exception.
Explanation
Explanation:
- Definition of Catching an Exception
- Catching an exception means that Python detects a runtime error (exception) and then executes a corresponding
exceptblock to handle it.- This prevents the program from terminating abruptly.
- How It Works
- Python executes the
tryblock.- If no exception occurs →
exceptblock is skipped.- If an exception occurs → Python searches for a matching
exceptblock.- When a matching
exceptblock is found and executed, the exception is considered caught.
- Benefits of Catching Exceptions
- Graceful error handling: The program can display an error message or take corrective action.
- Program continuity: The program does not crash and continues execution after the
exceptblock.- Robust code: Specific errors can be handled differently for better control.
Example:
try: x = int(input("Enter a number: ")) result = 10 / x except ZeroDivisionError: print("Cannot divide by zero!") # Exception caught here except ValueError: print("Invalid input!") # Exception caught here else: print("Result:", result)
- Input =
0→ZeroDivisionErroroccurs → caught by the firstexceptblock- Input =
abc→ValueErroroccurs → caught by the secondexceptblockSummary:
- An exception is caught only when the matching
exceptblock executes.- This allows error handling and prevents abrupt termination.
Exception Handling in Python is one of the most important topics in Class 12 Computer Science.
It helps students understand how Python deals with runtime errors and how programs can be made more reliable using try, except, else, and finally blocks.
By practicing these MCQs with detailed explanations, students can develop a strong conceptual foundation and perform better in their Board Exams as well as Python practical assessments.
Keep revising these questions and examples regularly — they not only help in exams but also improve your logical and programming skills for higher studies in computer science.
Computer Science Class XII NCERT book [Download]
Class 12 Computer Science MCQs [link]
