Exception Handling in Python

This page contains the NCERT Computer Science class 12 chapter 1 Exception Handling in Python. You can find the solutions for the chapter 1 of NCERT class 12 Computer Science Exercise. So is the case if you are looking for NCERT class 12 Computer Science related topic Exception Handling in Python questions and answers for the Exercise
Exercise
Question 1
1. “Every syntax error is an exception but every exception cannot be a syntax error.” Justify the statement.
Answer 1
A Syntax Error (also called a parsing error) happens when we break the rules of Python syntax while writing the program. In that case, the interpreter does not start executing the program until we fix it. So SyntaxError is an exception.
An Exception generally means an error that occurs during execution (runtime) even when the program is syntactically correct (example: division by zero, file not found, wrong input type). These are not syntax errors.
So:
Every syntax error is an exception (SyntaxError is an exception).
But many exceptions are runtime errors, so every exception is not a syntax error.
Question 2
2. When are the following built-in exceptions raised? Give examples to support your answers.
a)
ImportError
b)
IOError
c)
NameError
d)
ZeroDivisionError
Answer 2
a) ImportError
Answer: Raised when the requested module is not found.
# ImportError example
import abcdefgh  # module does not exist
Traceback (most recent call last):
  File "exception-handling-in-python-question_2_a.py", line 2, in <module>
    import abcdefgh  # module does not exist
    ^^^^^^^^^^^^^^^
ModuleNotFoundError: No module named 'abcdefgh'
b) IOError
Answer: Raised when a file specified in a program cannot be opened.
# IOError example (file not found / cannot open)
f = open("no_such_file.txt", "r")
Traceback (most recent call last):
  File "exception-handling-in-python-question_2_b.py", line 2, in <module>
    f = open("no_such_file.txt", "r")
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'no_such_file.txt'
c) NameError
Answer: Raised when a variable name is not defined.
# NameError example
print(total_marks)  # total_marks not defined
Traceback (most recent call last):
  File "exception-handling-in-python-question_2_c.py", line 2, in <module>
    print(total_marks)  # total_marks not defined
          ^^^^^^^^^^^
NameError: name 'total_marks' is not defined
d) ZeroDivisionError
Answer: Raised when the denominator in division is zero.
# ZeroDivisionError example
print(10 / 0)
Traceback (most recent call last):
  File "exception-handling-in-python-question_2_d.py", line 2, in <module>
    print(10 / 0)
          ~~~^~~
ZeroDivisionError: division by zero
Question 3
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).
Answer 3
Use of raise: raise is used to forcefully throw an exception. When we raise an exception, the normal flow of the program stops and control moves to an exception handler (if written).
# Program: Division with raise (raise exception if denominator is 0)

print("Division Program using raise")

# Read inputs (as integers)
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number (denominator): "))

# If denominator is 0, raise an exception manually
if num2 == 0:
    raise ZeroDivisionError("Denominator cannot be 0")

# If denominator is not 0, perform division
quotient = num1 / num2
print("Quotient =", quotient)
Division Program using raise
Enter the first number: 43
Enter the second number (denominator): 0
Traceback (most recent call last):
  File "exception-handling-in-python-question_3.py", line 11, in <module>
    raise ZeroDivisionError("Denominator cannot be 0")
ZeroDivisionError: Denominator cannot be 0
Question 4
4. Use assert statement in Question No. 3 to test the division expression in the program.
Answer 4
assert tests an expression. If it becomes False, Python raises AssertionError with an optional message.
# Program: Division using assert

print("Division Program using assert")

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number (denominator): "))

# Assert that denominator is not zero
assert (num2 != 0), "OOPS... Denominator should not be zero"

quotient = num1 / num2
print("Quotient =", quotient)
Division Program using assert
Enter the first number: 41
Enter the second number (denominator): 0
Traceback (most recent call last):
  File "exception-handling-in-python-question_4.py", line 9, in <module>
    assert (num2 != 0), "OOPS... Denominator should not be zero"
            ^^^^^^^^^
AssertionError: OOPS... Denominator should not be zero
Question 5
5. Define the following:
a)
Exception Handling
b)
Throwing an exception
c)
Catching an exception
Answer 5
a) Exception Handling: Writing extra code (exception handler) to handle runtime errors so the program does not crash abruptly, and shows proper messages/instructions.
b) Throwing an exception: When an error occurs, Python creates an exception object and hands it to the runtime system. This process is called throwing an exception.
c) Catching an exception: When the matching handler code runs (usually inside except), the exception is said to be caught.
Question 6
6. Explain catching exceptions using try and except block.
Answer 6
An exception is said to be caught when the code written to handle that exception gets executed.
How try and except help in catching exceptions:
Suspicious statements (where an exception may occur) are written inside the try block.
Every try block is followed by an except block that contains the handler code.
If an exception occurs, the remaining statements in the try block are skipped and control is transferred to the except block.
Syntax:
try:
    # program statements where exceptions might occur
except ExceptionName:
    # code for exception handling if ExceptionName occurs
Example:
# Using try..except block (handles ZeroDivisionError)

print("Practicing for try block")

try:
    # Code where exception might occur
    numerator = 50
    denom = int(input("Enter the denominator: "))

    # If denom becomes 0, this line raises ZeroDivisionError
    quotient = numerator / denom

    print(quotient)
    print("Division performed successfully")

except ZeroDivisionError:
    # Handler code (runs only when denom is 0)
    print("Denominator as ZERO.... not allowed")

# This line runs after try..except in both cases
print("OUTSIDE try..except block")
What happens when this program runs?
If the user enters a non-zero denominator, division happens, the message “Division performed successfully” is printed, the except block is skipped, and then “OUTSIDE try..except block” is printed.
If the user enters 0, execution of the try block stops, control moves to the except block, the message “Denominator as ZERO…. not allowed” is printed, and then “OUTSIDE try..except block” is printed.
Sample Output (When the user enters non-zero value as denominator):
Practicing for try block
Enter the denominator: 4
12.5
Division performed successfully
OUTSIDE try..except block
Sample Output (When the user enters the value of denominator as 0):
Practicing for try block
Enter the denominator: 0
Denominator as ZERO.... not allowed
OUTSIDE try..except block
Question 7
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")
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")
Answer 7
Code with the blanks filled-in: ValueError, ZeroDivisionError, finally.
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")

except ValueError:  # to enter only integers
    print("Please enter only numbers")

except ZeroDivisionError:  # Denominator should not be zero
    print("Number 2 should not be zero")

else:
    print("Great .. you are a good programmer")
    print("Quotient =", quotient)

finally:  # to be executed at the end
    print("JOB OVER... GO GET SOME REST")
Question 8
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.
Answer 8
Important note:
Wrong number of arguments usually causes TypeError.
ValueError happens when the value is invalid (example: math.sqrt(-9)). So below, we show both, and we specifically catch ValueError as asked.
Wrong usage of sqrt():
import math

print("Math module exception handling")

try:
    # This causes ValueError because sqrt of a negative number is not allowed
    n = int(input("Enter a number for square root: "))
    result = math.sqrt(n)
    print("Square root =", result)

except ValueError:
    print("ValueError: You entered an invalid value (example: negative number for sqrt).")

# Extra demo: wrong number of arguments causes TypeError (not ValueError)
try:
    # WRONG arguments: sqrt needs exactly 1 argument
    print(math.sqrt(4, 2))
except TypeError:
    print("TypeError: Wrong number of arguments given to sqrt().")
Math module exception handling
Enter a number for square root: 17
Square root = 4.123105625617661
TypeError: Wrong number of arguments given to sqrt().
Wrong usage of pow():
try:
    # WRONG arguments: pow needs exactly 2 or 3 arguments
    print(math.pow(2))  # missing exponent
except TypeError:
    print("TypeError: Wrong number of arguments given to pow().")
Sample Output:
Traceback (most recent call last):
  File "exception-handling-in-python-question_8.py", line 3, in <module>
    print(math.pow(2))  # missing exponent
NameError: name 'math' is not defined
Question 9
9. What is the use of finally clause? Use finally clause in the problem given in Question No. 7.
Answer 9
Answer (use of finally): The statements inside finally block are always executed, whether exception occurs or not. It is commonly used for cleanup work (like closing files).
Q7 updated code already includes finally:
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")

except ValueError:
    print("Please enter only numbers")

except ZeroDivisionError:
    print("Number 2 should not be zero")

else:
    print("Great .. you are a good programmer")
    print("Quotient =", quotient)

finally:
    # This will run in ALL cases
    print("JOB OVER... GO GET SOME REST")
Sample Output: When the ValueError exception is raised (when the input is not a number)
Learning Exceptions...
Enter the first number: ab
Please enter only numbers
JOB OVER... GO GET SOME REST
We can notice that the finally block is executed even when ValueError exception occurs.
Sample Output: When the ZeroDivisionError exception is raised (when the second number/divisor is zero)
Learning Exceptions...
Enter the first number: 23
Enter the second number: 0
Number 2 should not be zero
JOB OVER... GO GET SOME REST
We can notice that the finally block is executed even when ZeroDivisionError exception occurs.
Sample Output: When no exception is raised.
Learning Exceptions...
Enter the first number: 7
Enter the second number: 2
Both the numbers entered were correct
Great .. you are a good programmer
Quotient = 3.5
JOB OVER... GO GET SOME REST
We can notice that the finally block is executed even when no exception occurs.