Python Programming - Exception Handling

Exercise : Exception Handling - General Questions
  • Exception Handling - General Questions
31.
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.

32.
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.

33.
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?
"Error: invalid literal for int() with base 10: 'abc'"
"abc"
0
None
Answer: Option
Explanation:
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."

34.
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.

35.
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."