Exercise: Exception Handling
Questions for: Exception Handling
Consider the following Python code:
try:
result = 10 / 0
except ZeroDivisionError as e:
result = "Error: " + str(e)
What will be the value of "result" after the execution of this code?
A:
10
B:
0
C:
"Error: division by zero"
D:
None
Answer: C
The code attempts to divide by zero, resulting in a ZeroDivisionError. The exception is caught, and "result" is assigned the string "Error: division by zero."
What does the
with statement provide in Python for file handling?
A:
It raises exceptions
B:
It terminates the program
C:
It ensures proper resource cleanup
D:
It defines custom exception classes
Answer: C
The
with statement is used for file handling in Python and ensures proper resource cleanup by automatically closing the file when the block is exited, even if an exception occurs.Discuss About this Question.
Which of the following is a built-in exception in Python that is raised when a specified key is not found in a dictionary?
A:
KeyError
B:
ValueError
C:
NotFoundException
D:
MissingKeyError
Answer: A
A
KeyError is raised when attempting to access a key in a dictionary that does not exist.Discuss About this Question.
What is the purpose of the
AssertionError?
A:
It is a generic exception raised for all assert statements
B:
It is raised when an assertion fails
C:
It is raised when an
assert statement is not used
D:
It is raised when a
try block encounters an error
Answer: B
The
AssertionError is raised when an assert statement fails, indicating that a condition specified in the assert statement is False.Discuss About this Question.
Which of the following statements is true about the
try, except, and finally blocks?
A:
The
except block is mandatory if there is a finally block
B:
The
finally block is optional
C:
The
try block is optional
D:
The
except block is optional if there is a finally block
Answer: B
The
finally block is optional in exception handling. It can be used for cleanup operations and will be executed whether an exception occurs or not.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.