Exceptions in Python MCQ Quiz - Objective Question with Answer for Exceptions in Python - Download Free PDF
Last updated on Apr 15, 2025
Latest Exceptions in Python MCQ Objective Questions
Exceptions in Python Question 1:
This exeption occurs wherever a local or global variable name is not defined.
Answer (Detailed Solution Below)
Exceptions in Python Question 1 Detailed Solution
The correct answer is NameError.
Key Points
- A NameError is an exception in Python that occurs when a local or global variable name is not found.
- This can happen when you try to use a variable before it has been defined, or if you have a typo in the variable name.
- It is a common error, especially in larger codebases where variable names can be easily mistyped or forgotten.
Additional Information
- To avoid NameError, ensure that all variables are properly defined before they are used.
- Using meaningful variable names and maintaining consistency can help reduce the likelihood of this error.
- Here is an example of a NameError in Python:
def print_variable():
print(my_variable)
print_variable()
In the code above, my_variable
is not defined before it is used, resulting in a NameError.
Exceptions in Python Question 2:
The statements inside the ________ block are always executed regardless of whether an exception occured in the ________ block or not. What will be the appropriate clause in above statement respectively.
Answer (Detailed Solution Below)
Exceptions in Python Question 2 Detailed Solution
The correct answer is finally, try.
Key Points
- In programming, especially in languages like Python, the finally block is used for code that must be executed no matter what.
- The try block is used to wrap code that may potentially cause an exception.
- Regardless of whether an exception occurs in the try block or not, the code inside the finally block will always execute.
- This ensures that crucial cleanup or finalization code runs, such as closing a file or releasing resources.
Additional Information
- Here's an example of how the try and finally blocks are used in Python:
try:
# Code that may cause an exception
print("Inside try block")
x = 1 / 0 # This will cause a ZeroDivisionError
finally:
# Code that will run no matter what
print("Inside finally block")
- In the above example, even though an exception occurs in the try block, the finally block still gets executed.
- This behavior is critical for ensuring that necessary cleanup actions are performed.
Exceptions in Python Question 3:
Which error is generated by pickle.load() function, when you reach end - of - file, while reading from the file.
Answer (Detailed Solution Below)
Exceptions in Python Question 3 Detailed Solution
The correct answer is EOF error.
Key Points
- EOF error stands for End Of File error.
- This error occurs when the pickle.load() function attempts to read beyond the end of the file.
- It signifies that the file reading operation has reached the end of the file without finding the expected data structure.
- Proper handling of EOFError is essential to avoid unexpected program crashes.
Additional Information
- EOFError is a built-in exception in Python.
- Other common file-related errors include FileNotFoundError and IOError.
- It is good practice to use try-except blocks to handle EOFError when working with file operations.
- Below is an example of handling EOFError while using the pickle module:
import pickle
# Sample data to be pickled
data = {'key': 'value'}
# Pickling the data
with open('data.pkl', 'wb') as file:
pickle.dump(data, file)
# Unpickling the data with EOFError handling
try:
with open('data.pkl', 'rb') as file:
while True:
try:
item = pickle.load(file)
print(item)
except EOFError:
print("End of file reached")
break
except FileNotFoundError:
print("File not found")
Exceptions in Python Question 4:
Match List I with List II
LIST I |
LIST II |
||
A. |
writelines |
I. |
module for binary files |
B. |
pickle |
II. |
opening and reading a binary file |
C. |
try-except |
III. |
writing a sequence of string |
D. |
rb |
IV. |
exception handling |
Choose the correct answer from the options given below:
Answer (Detailed Solution Below)
Exceptions in Python Question 4 Detailed Solution
The correct answer is Option 4.
- A writelines is associated with writing a sequence of string.
- B pickle is associated with module for binary files.
- C try-except is associated with exception handling.
- D rb is associated with opening and reading a binary file.
- The writelines method is used to write a sequence of strings to a file.
- The pickle module is used for serializing and deserializing Python objects, which is often used for working with binary files.
- The try-except block is a fundamental concept in Python for handling exceptions and errors in code.
- The mode rb is used to open a file for reading in binary format.
Exceptions in Python Question 5:
Arrange the following in correct order of exception handling in python :
(A) Write the code that may raise an exception inside a try block
(B) Execute some code regardless of whether the exception occurs or not using the finally block
(C) Handle the specific exception using the except block
(D) Raise the exception using the raise statement if necessary
Choose the correct answer from the options given below:
Answer (Detailed Solution Below)
Exceptions in Python Question 5 Detailed Solution
The correct answer is Option 2: (A), (C), (B), (D).
Exception Handling in Python
To handle exceptions in Python, you should follow a particular sequence of steps to ensure that exceptions are properly managed and that your program can recover or terminate gracefully. The correct order of exception handling in Python is as follows:
- Write the code that may raise an exception inside a try block.
- Handle the specific exception using the except block.
- Execute some code regardless of whether the exception occurs or not using the finally block.
- Raise the exception using the raise statement if necessary.
The correct answer is Option 2: (A), (C), (B), (D).
Key Points
- Python provides a robust framework for managing errors and exceptions using try, except, finally, and raise statements.
- Placing code that may raise an exception inside a try block helps isolate the error-prone code from the rest of the program.
- Using the except block, you can catch and handle specific exceptions, preventing the program from crashing unexpectedly.
- The finally block allows you to execute code that must run regardless of whether an exception occurred, such as closing files or releasing resources.
- The raise statement can be used to trigger an exception manually if a certain condition is met, allowing for custom error handling.
Additional Information
- Exception handling improves the robustness and reliability of your code by allowing you to manage and respond to unexpected errors gracefully.
- Multiple except blocks can be used to handle different types of exceptions separately, providing more granular control over error handling.
- Using the else block, you can execute code that should run only if no exceptions are raised in the try block.
- Properly handling exceptions is crucial for developing secure and stable applications, especially in production environments.
Top Exceptions in Python MCQ Objective Questions
Which statement is/are true about Exception handling?
i. There can be try block without catch block but vice versa is not possible.
ii. There is no limit on the number of catch, block corresponding to a try block.
iii. The object must be created of a specific class of which the error has occurred otherwise runtime error will occur.
iv. To execute a code with each and every run of program, the code is written in finally block.
Answer (Detailed Solution Below)
Exceptions in Python Question 6 Detailed Solution
Download Solution PDFThe correct answer is option 1.
Concept:
Statement 1: There can try block without catch block but vice versa is not possible.
True, there may or may not be a catch block in the try block. But without a try block, a catch block cannot exist in a program. Similar to if-block, else-block can only be written if and only if it is present in the program.
Statement 2: There is no limit on the number of catches, or blocks corresponding to a try block.
True, there is no limit on the number of catch blocks corresponding to a try block. This is because the error can be of any type and for each type, a new catch block can be defined. This is to make sure all types of exceptions can be handled.
Statement 3: The object must be created of a specific class of which the error has occurred otherwise runtime error will occur.
False, We can also create an object of a class and access it in another class. This is often used for better organization of classes.
Statement 4: To execute a code with each and every run of the program, the code is written in the finally block.
True, Whether an exception is handled or not, the finally block is always run. Since the exception may or may not occur, it comprises all the required statements that must be printed. After the try-catch block comes the finally block.
Hence the correct answer is i and ii, iv.
Exceptions in Python Question 7:
In Python code, on encountering a syntax error, the _____________ does not execute the program.
Answer (Detailed Solution Below)
Exceptions in Python Question 7 Detailed Solution
The correct answer is option 3.
Concept:
Python is a programming language that is commonly used to create websites and applications, automate operations, and do data analysis. Python is a general-purpose programming language, which means it can be used to develop a wide range of applications and isn't tailored to any particular issue.
- The interpreter parses our Python code before converting it to Python byte code, which it then executes.
- During this initial step of program execution, also known as parsing, the interpreter will look for any incorrect syntax in Python.
- If the interpreter fails to parse our Python code, we have used improper syntax somewhere. The interpreter will try to show us where we made the mistake.
- In Python code, on encountering a syntax error, the Interpreter does not execute the program.
Hence the correct answer is Interpreter.
Exceptions in Python Question 8:
What will be the output of the following Python code:
a=5.2
try:
print(a)
except NameError:
print("Variable a is not defined")
except ValueError:
print("The value of a must be an integer")
Answer (Detailed Solution Below)
Exceptions in Python Question 8 Detailed Solution
The correct option is 5.2
CONCEPT:
In python, a variable is created when we first assign a value to it. We are not required to declare a variable beforehand.
so print(a) statement in try block will print 5.2 as output successfully and hence no exception occurs.
In the above question
Option 1 The value of a must be an integer / ValueError appears when a value is not of the expected type. But here it is not the case.
Option 2 Variable a is not defined / NameError is raised when the identifier is accessed before being defined in the local or global scope. But here "a" is already defined.
Option 3 "5.2" / Correct Option
Option 4 "5" / Variable "a" if of type float, so integer 5 cannot be printed until we type case it as int(a).
Exceptions in Python Question 9:
Which of the following error will be raised by the given Python code:
randomList = ['a', 2, 3]
for element in randomList:
print("The element is ", element)
x = int(element+1)
print("The incremeant of ", element, "is", x)
Answer (Detailed Solution Below)
Exceptions in Python Question 9 Detailed Solution
Correct Option TypeError
CONCEPT:
Type Error occurs when the data type of objects in an operation is inappropriate.
Example dividing an integer with a string.
In the above question, a for loop is executing through the list which tries to increment the value of each element of the list by 1 and store it in variable x.
" x=int(element + 1) " but will result in type error when it tries to increment the element 'a' at index 0 of the list by 1.
This is because 'a' is of type string and we cannot add an integer to a string.
Exceptions in Python Question 10:
What will be the output of the following Python code:
a = [4, 5, 6, 7]
try:
print ("First element is %d" %(a[2]))
print ("Fifth element is %d" %(a[5]))
except:
print ("Error")
Answer (Detailed Solution Below)
First element is 6
Error
Exceptions in Python Question 10 Detailed Solution
Correct option:
First element is 6
Error
Concept:
Try and Except statement is used to handle errors within code in Python. The code inside the try block will execute when there is no error in the program.
Whereas the code inside the except block will execute whenever the program encounters some error in the execution of the try block.
Syntax:
try:
# Code
except:
# Executed if there is an error in the try block
Explanation:
Here the first statement in the try block is executed successfully as it is trying to access the 2nd index of the list. This statement will print "First element is 6".
But the second statement in the try block is trying to access the 5th index which will throw the error "List index out of range", as the length of the array is 4 (i.e index range 0-3) and there is no 5th index in the list.
This will lead to the execution of except block to handle the exception. This will print "Error" in the output.
Exceptions in Python Question 11:
Which type of error will be raised by the following Python code:
x = 10
y = 20
if (y > x)
print("y is greater than x")
Answer (Detailed Solution Below)
Exceptions in Python Question 11 Detailed Solution
The correct option is Syntax Error
CONCEPT:
Syntax errors occur when the programmer does not follow or makes mistake in the syntax of a particular programming language
Common syntax errors in python:
- leaving out a keyword.
- misspelling a keyword.
- leaving out a symbol, such as a comma, brackets, or colon.
Syntax:
if condition:
# code to execute in case if the above condition is true
In the above question:
Option 1 ValueError / appears when a value is not of the expected type. Example: int("Test") ValueError: int() cannot convert 'Test' into an integer.
Option 2 TypeError / occurs when the data type of objects in an operation is inappropriate. Example dividing an integer with a string.
Option 3 IOError / error raised when an input/output operation fails.
Exceptions in Python Question 12:
Which of the following is not a built-in exceptions in Python?
Answer (Detailed Solution Below)
Exceptions in Python Question 12 Detailed Solution
The correct answer is option 4.
Concept:
Built-in exceptions are the exceptions that are available in Python libraries. These exceptions are suitable to explain certain error situations. Some of the commonly occurring built-in exceptions are SyntaxError, ValueError, IOError, KeyboardInterrupt, ImportError, EOFError, ZeroDivisionError, IndexError, NameError, IndentationError, TypeError,and OverFlowerror.
ZeroDivisionError:
It is raised when the denominator in a division operation is zero.
OverFlowError:
It is raised when the result of a calculation exceeds the maximum limit for the numeric data type.
KeyboardInterrupt:
It is raised when the user accidentally hits the Delete or Esc key while executing a program due to which the normal flow of the program is interrupted.
SyntaxError:
It is raised when there is an error in the syntax of the Python code.
ValueError:
It is raised when a built-in method or operation receives an argument that has the right data type but mismatched or inappropriate values.
IOError:
It is raised when the file specified in a program statement cannot be opened.
ImportError:
It is raised when the requested module definition is not found.
EOFError:
It is raised when the end of the file condition is reached without reading any data by input().
Hence the correct answer is None of the above.
Exceptions in Python Question 13:
What will be the output of the following Python code:
a = 1
if (a = 2):
print("value of a is", a)
Answer (Detailed Solution Below)
Exceptions in Python Question 13 Detailed Solution
The correct option is Syntax Error
CONCEPT:
Syntax errors occur when the programmer does not follow or makes mistake in the syntax of a particular programming language
Common syntax errors in python:
- leaving out a keyword.
- misspelling a keyword.
- leaving out a symbol, such as a comma, brackets....etc.
In Python, assignment using `=` operator is not allowed inside an condition of if statement
The error thrown will be "SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '=' ".
Syntax of if statement in python:
if condition:
# code to execute in case if the above condition is true
Additional Information
IOError is raised when an input/output operation fails.
Exceptions in Python Question 14:
Consider the following Python code and identify the line number(s) which has some error. Assume that the user wants to print the reverse of the given list:
languages = ['java','python','C++'] #List
for i in range(len(languages),0,-1): #Line-1
print(Languages[i],end=' ') #Line-2
Answer (Detailed Solution Below)
Exceptions in Python Question 14 Detailed Solution
In the given code both Line-1 and Line-2 have errors.
The given code is described as:
- The list named as language is initialized with three strings (java, python, C++).
- In line-1 the for loop is defined, where the variable i is initialized to traverse the index of the list.
- In the initial condition of the for loop, the len(language) is used to return the size of the list which is 3.
- In the termination condition of for loop, the given value is 0, which means the loop can run till index 1 and will not accept 0.
- In the iteration condition, the given value is -1, which means the loop move from the upper index to the lower index by 1. For instance, from 3 to 2.
- The print() statements to print the list named with Language[i] whose index value is i.
- This end=' ' statement leaves the space after each string printed from the list.
Error in Line-1:
- A list index out of range error, the len(language) returns 3, so the loop starts from index 3, but the list only contains index till 2 as the list starts from 0 and has 3 strings.
- The termination condition must contain -1, because the loop needs to run till index 0.
Error in Line-2:
- Indentation error, because the print statement must be at one tab space to fall under the for-loop.
- Name error, the list name "Language" must start in lower case in the print statement, as per the original name.
The correct code will be like:
languages = ['java','python','C++'] #List
for i in range(len(languages)-1,-1,-1): #Line-1
print(languages[i],end=' ') #Line-2
The output list will be:
['c++' , 'python', 'java']
Exceptions in Python Question 15:
Answer (Detailed Solution Below)
Exceptions in Python Question 15 Detailed Solution
The correct option is SyntaxError
CONCEPT:
- Syntax errors are produced by the python interpreter when it is translating the source code into byte code line by line.
- These errors usually indicate that there is something wrong with the syntax of the program.
- Example: Omitting the colon at the end of a def, if, for, while statement yields SyntaxError: invalid syntax.
- In the above question, the condition (a=1) in the if statement tries to assign value to a rather than comparing it.
- This will result in syntax errors.