Exercise: Exception Handling
Questions for: Exception Handling
What is the purpose of the
with statement 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.
Consider the following Python code:
try:
x = int("abc")
except ValueError as e:
x = "Error: " + str(e)
What will be the value of "x" after the execution of this code?
A:
"Error: invalid literal for int() with base 10: 'abc'"
B:
"abc"
C:
0
D:
None
Answer: A
The
try block attempts to convert the string "abc" to an integer, causing a ValueError. The except block captures the exception and assigns an error message to "x."Discuss About this Question.
What is the purpose of the
sys.exc_info() function?
A:
To define custom exception classes
B:
To terminate the program immediately
C:
To retrieve information about the currently handled exception
D:
To raise exceptions intentionally
Answer: C
sys.exc_info() returns a tuple of information about the currently handled exception, including the type, value, and traceback.Discuss About this Question.
What is the purpose of the
try, except, else, and finally blocks collectively?
A:
To define custom exception classes
B:
To terminate the program immediately
C:
To handle and catch exceptions, execute code when no exception occurs, and always execute code, respectively
D:
To raise exceptions intentionally
Answer: C
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.
Discuss About this Question.
Which of the following is a built-in exception in Python for handling errors related to importing modules that do not exist?
A:
ImportError
B:
ModuleNotFoundError
C:
NoSuchModuleError
D:
ModuleImportError
Answer: B
ModuleNotFoundError is raised when attempting to import a module that does not exist.
Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.