Python Programming - Exception Handling

Exercise : Exception Handling - General Questions
  • Exception Handling - General Questions
11.
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?
42
"42"
"Invalid conversion"
43
Answer: Option
Explanation:
The try block successfully converts the string "42" to an integer. The else block increments the value of "x" by 1.

12.
Which built-in Python function is used to raise an exception?
raise()
throw()
except()
error()
Answer: Option
Explanation:
The raise() function is used to explicitly raise an exception in Python.

13.
In Python, what is the purpose of the except block without specifying an exception type?
It catches all exceptions
It is a syntax error
It only catches specific exceptions
It is not allowed
Answer: Option
Explanation:
An except block without specifying an exception type catches all exceptions, which can be useful for handling unexpected errors.

14.
Consider the following Python code:
try:
    value = int("abc")
except ValueError:
    result = "Invalid conversion"
finally:
    result += " - Finally block executed"
What will be the value of "result" after the execution of this code?
"Invalid conversion"
"Invalid conversion - Finally block executed"
" - Finally block executed"
Raises an exception
Answer: Option
Explanation:
The finally block is executed regardless of whether an exception occurs or not. It appends " - Finally block executed" to the "result" string.

15.
Which of the following statements is true about the raise statement?
It is used to terminate the program
It can only raise built-in exceptions
It is used to catch exceptions
It is used to explicitly raise an exception
Answer: Option
Explanation:
The raise statement is used to explicitly raise an exception in Python.