Exception Handling in Python - Descriptive Questions with Answers
Q: 1. "Every syntax error is an exception but every exception cannot be a syntax error."
Justify the statement.
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("[Link]")`
when file does not exist.
c) NameError: Raised when a variable is not defined. Example: `print(x)` without defining x.
d) ZeroDivisionError: Raised when dividing a number by zero. Example: `10 / 0`.
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
(denominator) as zero (0).
Ans: The raise statement is used to manually throw an exception in Python.
Example code:
Exception Handling in Python - Descriptive Questions with Answers
try:
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
if num2 == 0:
raise ZeroDivisionError("Denominator cannot be zero!")
print("Quotient:", num1 / num2)
except ZeroDivisionError as e:
print("Error:", e)
Q: 4. Use assert statement in Question No. 3 to test the division expression in the program.
Ans: Using assert to test the division expression:
def divide(a, b):
assert b != 0, "Denominator cannot be zero!"
return a / b
try:
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
print("Quotient:", divide(num1, num2))
except AssertionError as e:
print("Error:", e)
Q: 5. Define the following:
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,
except, else, and finally.
b) Throwing an Exception: When Python detects an error and creates an exception object to pass to
the runtime system.
c) Catching an Exception: When the program finds matching handler code and executes it to handle
the exception.
Q: 6. Explain catching exceptions using try and except block.
Ans: Catching exceptions involves placing error-prone code in a try block and handling specific
exceptions using one or more except blocks.
Example:
try:
x = int(input("Enter a number: "))
print(10 / x)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Please enter a valid number.")
Q: 7. Consider the code given below and fill in the blanks.
print (" Learning Exceptions...")
try:
num1= int(input ("Enter the first number"))
num2=int(input("Enter the second number"))
quotient=(num1/num2)
print ("Both the numbers entered were correct")
Exception Handling in Python - Descriptive Questions with Answers
except _____________: # to enter only integers
print (" Please enter only numbers")
except ____________: # Denominator should not be zero
print(" Number 2 should not be zero")
else:
print(" Great .. you are a good programmer")
___________: # to be executed at the end
print(" JOB OVER... GO GET SOME REST")
Ans: except ValueError: # to enter only integers
except ZeroDivisionError: # Denominator should not be zero
finally: # to be executed at the end
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
process to catch the ValueError exception.
Ans: Example using math module with wrong number of arguments:
import math
try:
print([Link](25, 2)) # Incorrect usage
except TypeError:
print("TypeError: Wrong number of arguments used in function.")
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:
print("JOB OVER... GO GET SOME REST")