Python Programming - Exception Handling

Exercise : Exception Handling - General Questions
  • Exception Handling - General Questions
1.
In Python, what is the purpose of the assert statement?
To handle exceptions
To define custom exception classes
To check if a condition is True, otherwise raise an AssertionError
To terminate the program immediately
Answer: Option
Explanation:
The assert statement is used to check if a condition is True. If the condition is False, it raises an AssertionError, allowing you to catch unexpected conditions during development.

2.
Consider the following Python code:
try:
    result = 10 / 0
except ZeroDivisionError:
    result = "Error: Division by zero"
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, which raises a ZeroDivisionError. The exception is caught, and "result" is assigned the string "Error: Division by zero."

3.
Which of the following is a built-in exception in Python for handling errors related to accessing a key that does not exist in a dictionary?
KeyError
ValueNotFoundError
NoSuchElementError
DictionaryError
Answer: Option
Explanation:
A KeyError is raised when attempting to access a key in a dictionary that does not exist.

4.
In Python, what is the purpose of the else block in exception handling?
It is executed if an exception occurs
It is used to define custom exception classes
It is executed if no exception occurs in the try block
It is used to raise exceptions
Answer: Option
Explanation:
The else block is executed only if no exceptions are raised in the associated "try" block. It is used to specify code that should run when there are no exceptions.

5.
What is the purpose of the pass statement in exception handling?
To re-raise an exception
To ignore an exception and continue with the program execution
To define custom exception classes
To print the exception message
Answer: Option
Explanation:
The pass statement is used as a placeholder to ignore an exception and continue with the program execution when no action is required.