Python Programming - Exception Handling

Exercise : Exception Handling - General Questions
  • Exception Handling - General Questions
16.
Consider the following Python code:
try:
    x = int("42")
except ValueError:
    x = "Invalid conversion"
else:
    x += 1
finally:
    x *= 2
What will be the value of "x" after the execution of this code?
42
"42"
"Invalid conversion"
86
Answer: Option
Explanation:
The try block successfully converts the string "42" to an integer. The else block increments the value of "x" by 1, and the finally block multiplies "x" by 2.

17.
Which of the following statements is true about the try, except, and finally blocks?
The except block is mandatory if there is a finally block
The finally block is optional
The try block is optional
The except block is optional if there is a finally block
Answer: Option
Explanation:
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.

18.
What is the purpose of the AssertionError?
It is a generic exception raised for all assert statements
It is raised when an assertion fails
It is raised when an assert statement is not used
It is raised when a try block encounters an error
Answer: Option
Explanation:
The AssertionError is raised when an assert statement fails, indicating that a condition specified in the assert statement is False.

19.
Which of the following is a built-in exception in Python that is raised when a specified key is not found in a dictionary?
KeyError
ValueError
NotFoundException
MissingKeyError
Answer: Option
Explanation:
A KeyError is raised when attempting to access a key in a dictionary that does not exist.

20.
What does the with statement provide in Python for file handling?
It raises exceptions
It terminates the program
It ensures proper resource cleanup
It defines custom exception classes
Answer: Option
Explanation:
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.