Python Programming - Exception Handling

Exercise : Exception Handling - General Questions
  • Exception Handling - General Questions
21.
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?
10
0
"Error: division by zero"
None
Answer: Option
Explanation:
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."

22.
Which of the following is a built-in exception in Python for handling errors related to importing modules that do not exist?
ImportError
ModuleNotFoundError
NoSuchModuleError
ModuleImportError
Answer: Option
Explanation:
ModuleNotFoundError is raised when attempting to import a module that does not exist.

23.
What is the purpose of the try, except, else, and finally blocks collectively?
To define custom exception classes
To terminate the program immediately
To handle and catch exceptions, execute code when no exception occurs, and always execute code, respectively
To raise exceptions intentionally
Answer: Option
Explanation:
The combination of these blocks provides comprehensive exception handling in Python, allowing for handling exceptions, executing code when no exception occurs, and always executing code.

24.
What is the purpose of the sys.exc_info() function?
To define custom exception classes
To terminate the program immediately
To retrieve information about the currently handled exception
To raise exceptions intentionally
Answer: Option
Explanation:
sys.exc_info() returns a tuple of information about the currently handled exception, including the type, value, and traceback.

25.
Consider the following Python code:
try:
    value = int("abc")
except ValueError:
    result = "Invalid conversion"
finally:
    result += " - Finally block executed"
What will be the value of "result" after the execution of this code?
"Invalid conversion"
"Invalid conversion - Finally block executed"
" - Finally block executed"
Raises an exception
Answer: Option
Explanation:
The finally block is executed regardless of whether an exception occurs or not. It appends " - Finally block executed" to the "result" string.