Exception_Handling_Descriptive_QA_Clean
Exception_Handling_Descriptive_QA_Clean
Q: 1. "Every syntax error is an exception but every exception cannot be a syntax error."
Ans: Every syntax error is an exception because Python treats syntax issues like missing colons,
incorrect indentation, or invalid expressions as parsing errors that are caught before code execution.
However, not every exception is a syntax error. Other exceptions like ZeroDivisionError, NameError,
or ValueError occur during runtime after the code has passed syntax checks. Hence, while all syntax
errors are exceptions, many exceptions arise due to logic or runtime errors, not syntax problems.
Q: 2. When are the following built-in exceptions raised? Give examples to support your
answers.
a) ImportError
b) IOError
c) NameError
d) ZeroDivisionError
Ans: a) ImportError: Raised when a module cannot be found. Example: `import maths` will raise
ImportError.
b) IOError: Raised when an input/output operation like file opening fails. Example: `open("file.txt")`
c) NameError: Raised when a variable is not defined. Example: `print(x)` without defining x.
Q: 3. What is the use of a raise statement? Write a code to accept two numbers and display
the quotient. Appropriate exception should be raised if the user enters the second number
Example code:
Exception Handling in Python - Descriptive Questions with Answers
try:
if num2 == 0:
except ZeroDivisionError as e:
print("Error:", e)
Q: 4. Use assert statement in Question No. 3 to test the division expression in the program.
return a / b
try:
except AssertionError as e:
print("Error:", e)
a) Exception Handling
b) Throwing an exception
c) Catching an exception
Exception Handling in Python - Descriptive Questions with Answers
Ans: a) Exception Handling: Process of handling runtime errors to avoid program crash using try,
b) Throwing an Exception: When Python detects an error and creates an exception object to pass to
c) Catching an Exception: When the program finds matching handler code and executes it to handle
the exception.
Ans: Catching exceptions involves placing error-prone code in a try block and handling specific
Example:
try:
print(10 / x)
except ZeroDivisionError:
except ValueError:
try:
quotient=(num1/num2)
else:
Q: 8. You have learnt how to use math module in Class XI. Write a code where you use the
wrong number of arguments for a method (say sqrt() or pow()). Use the exception handling
import math
try:
except TypeError:
Q: 9. What is the use of finally clause? Use finally clause in the problem given in Question
No. 7.
Ans: The finally clause is used to ensure that certain code (like file closing or cleanup) runs no
matter what.
Exception Handling in Python - Descriptive Questions with Answers
Used in Q7 as:
finally: