Professional Documents
Culture Documents
Exception Mcqs
Exception Mcqs
- A) try
- B) catch
- C) except
- D) handle
- Answer: C) except
3. In a try-except block, where should the code that might raise an exception be placed?
4. Which of the following statements is true about the "finally" block in Python?
- A) KeyError
- B) ValueError
- C) IndexError
- D) SyntaxError
- Answer: A) KeyError
- B) It catches an exception.
- C) It ignores an exception.
- D) It handles an exception
- A) error()
- B) raise()
- C) exception()
- D) throw()
-Answer: B) raise()
- B) Multiple except blocks can be used, each handling a specific type of exception.
- C) Multiple except blocks can be used, but they must all handle the same type of exception.
- D) To handle exceptions.
- A) FileNotFoundError
- B) ZeroDivisionError
- C) TypeMismatchError
- D) ValueError
-Answer: C) TypeMismatchError
1.
try:
print("Hello")
except ValueError as e:
print(e)
finally:
print("World")
Output:
Hello
Custom error
World
**Explanation:** The code prints "Hello", raises a ValueError with a custom message, catches the
ValueError in the except block, prints the error message, and then executes the finally block which
prints "World".
2. try:
num = 10 / 0
print(num)
except ZeroDivisionError:
print("Division by zero!")
Output:
Division by zero!
Explanation: The code attempts to divide by zero, which raises a ZeroDivisionError. This error is
caught in the except block and "Division by zero!" is printed.
3.
try:
num = int("ten")
print(num)
except ValueError:
print("Conversion error!")
finally:
print("End of program")
Output:
Conversion error!
End of program
Explanation: The code attempts to convert the string "ten" to an integer, which raises a ValueError.
This error is caught in the except block and "Conversion error!" is printed. The finally block is always
executed, printing "End of program".
4.
try:
raise Exception("An exception occurred!")
except ValueError:
print("Caught a ValueError")
except Exception as e:
print(e)
Output:
An exception occurred!
Explanation:The code raises an Exception with a custom message. Since there is no specific handler
for Exception, it goes to the general except block, printing the exception message.
5. Question:
try:
with open("nonexistent_file.txt") as f:
content = f.read()
except FileNotFoundError:
Predicted Output:
Explanation: The code tries to open a file that doesn't exist, which raises a FileNotFoundError. This
error is caught in the except block and "File not found!" is printed.