Exercise: Exception Handling

Questions for: Exception Handling

Consider the following Python code:
try:
    x = int("42")
except ValueError:
    x = "Invalid conversion"
else:
    x += 1
What will be the value of "x" after the execution of this code?
A:
42
B:
"42"
C:
"Invalid conversion"
D:
43
Answer: D
The try block successfully converts the string "42" to an integer. The else block increments the value of "x" by 1.
What is the purpose of the finally block in Python exception handling?
A:
Define custom exception classes
B:
Terminate the program
C:
Execute code regardless of whether an exception is raised or not
D:
Raise exceptions intentionally
Answer: C
The finally block contains code that will be executed no matter what, whether an exception is raised or not. It is useful for cleanup operations or releasing resources.
In Python, what will happen if an exception is not caught?
A:
The program will continue executing normally
B:
The program will terminate immediately
C:
The program will prompt the user to handle the exception
D:
The program will enter an infinite loop
Answer: B
If an exception is not caught, the program will terminate abruptly, and an error message will be displayed.
Which of the following is NOT a built-in exception in Python for handling errors related to accessing a key that does not exist in a dictionary?
A:
KeyError
B:
ValueError
C:
NoSuchKeyError
D:
NameError
Answer: C
NoSuchKeyError is not specifically related to accessing keys in a dictionary.
Consider the following Python code:
try:
    num = int("abc")
except ValueError:
    print("Invalid conversion")
else:
    print("Conversion successful")
What will be the output of this code?
A:
Invalid conversion
B:
Conversion successful
C:
ValueError: invalid literal for int() with base 10: 'abc'
D:
No output, it will raise an exception
Answer: A
The try block attempts to convert the string "abc" to an integer, resulting in a ValueError. The except block is executed, printing "Invalid conversion."
Ad Slot (Above Pagination)
Quiz