Python Programming - Exception Handling

Exercise : Exception Handling - General Questions
  • Exception Handling - General Questions
6.
What does the try and except blocks in Python exception handling allow you to do?
Define custom exception classes
Raise exceptions intentionally
Handle and catch exceptions
Terminate the program
Answer: Option
Explanation:
The try block is used to enclose code that might raise an exception, and the except block is used to handle and catch the raised exceptions.

7.
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?
Invalid conversion
Conversion successful
ValueError: invalid literal for int() with base 10: 'abc'
No output, it will raise an exception
Answer: Option
Explanation:
The try block attempts to convert the string "abc" to an integer, resulting in a ValueError. The except block is executed, printing "Invalid conversion."

8.
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?
KeyError
ValueError
NoSuchKeyError
NameError
Answer: Option
Explanation:
NameError is not specifically related to accessing keys in a dictionary.

9.
In Python, what will happen if an exception is not caught?
The program will continue executing normally
The program will terminate immediately
The program will prompt the user to handle the exception
The program will enter an infinite loop
Answer: Option
Explanation:
If an exception is not caught, the program will terminate abruptly, and an error message will be displayed.

10.
What is the purpose of the finally block in Python exception handling?
Define custom exception classes
Terminate the program
Execute code regardless of whether an exception is raised or not
Raise exceptions intentionally
Answer: Option
Explanation:
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.