Class 12 Computer Science – Exception Handling in Python NCERT Exercise Solutions

Exception Handling in Python NCERT Exercise Solutions

Class 12 Computer Science

Summary

  • Syntax errors or parsing errors are detected when we have not followed the rules of the particular programming language while writing a program.
  • When syntax error is encountered, Python displays the name of the error and a small description about the error.
  • The execution of the program will start only after the syntax error is rectified.
  • An exception is a Python object that represents an error.
  • Syntax errors are also handled as exceptions.
  • The exception needs to be handled by the programmer so that the program does not terminate abruptly.
  • When an exception occurs during execution of a program and there is a built-in exception defined for that, the error message written in that exception is displayed. The programmer then has to take appropriate action and handle it.
  • Some of the commonly occurring built-in exceptions are SyntaxError, ValueError, IOError, KeyboardInterrupt, ImportError, EOFError, ZeroDivisionError, IndexError, NameError, IndentationError, TypeError,and OverFlowerror.
  • When an error is encountered in a program, Python interpreter raises or throws an exception.
  • Exception Handlers are the codes that are designed to execute when a specific exception is raised.
  • Raising an exception involves interrupting the normal flow of the program execution and jumping to the exception handler.
  • Raise and assert statements are used to raise exceptions.
  • The process of exception handling involves writing additional code to give proper messages or instructions to the user. This prevents the program from crashing abruptly. The additional code is known as an exception handler.
  • An exception is said to be caught when a code that is designed to handle a particular exception is executed.
  • An exception is caught in the try block and handles in except block.
  • The statements inside the finally block are always executed regardless of whether an exception occurred in the try block or not.

Exception Handling in Python


Exercise with Solutions


1. “Every syntax error is an exception but every exception cannot be a syntax error.” Justify the statement.

Answer:

Exception is an error which occurs at Run Time, due to Syntax Errors, Run Time Errors or Logical Errors. In Python Exceptions are triggered automatically. It can be called forcefully also by using the code.

Syntax Error means errors occurs at compile time, due to not followed the rules of Python Programming Language. These errors are also known as parsing errors. On encountering a syntax error, the interpreter does not execute the program unless we rectify the errors, save and rerun the program. When a syntax error is encountered while working in shell mode, Python displays the name of the error and a small description about the error.

Because Exception can be occurred due to Syntax Errors, Logical Error and Run Time Errors, while Syntax errors occurs only due to syntax. So that “Every syntax error is an exception but every exception cannot be a syntax error.”


2. When are the following built-in exceptions raised? Give examples to support your answers.
a) ImportError
b) IOError
c) NameError
d) ZeroDivisionError

Answer:

(a) ImportError :- It is raised when the requested module definition is not found.

       >>> import maths
       Traceback (most recent call last):
         File "", line 1, in 
           import maths
       ModuleNotFoundError: No module named 'maths'

       >>> import randoms
       Traceback (most recent call last):
         File "", line 1, in 
           import randoms
       ModuleNotFoundError: No module named 'randoms'         

import maths #Raise an ImportError, due to maths module does not exists.

(b) IOError :- It is raised when the file specified in a program statement cannot be opened.

       >>> f = open("abc.txt",'r')
       Traceback (most recent call last):
         File "", line 1, in 
           f = open("abc.txt",'r')
       FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'         

(c) NameError :- It is raised when a local or global variable name is not defined.

       >>> print(name)
       Traceback (most recent call last):
         File "", line 1, in 
           print(name)
       NameError: name 'name' is not defined  

(d) ZeroDivisionError :- It is raised when the denominator in a division operation is zero.

       >>> 10/0
       Traceback (most recent call last):
         File "", line 1, in 
           10/0
       ZeroDivisionError: division by zero         

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: The raise statement can be used to throw an exception.

The syntax of raise statement is: raise exception-name[(optional argument)]

The argument is generally a string that is displayed when the exception is raised.

Code to accept two numbers and display the quotient.
 n = int(input("Enter Number 1 :"))
 m = int(input("Enter Number 2 : "))
 if m == 0:
     raise ZeroDivisionError
 else:
     print("Quotient : ", n / m)

4. Use assert statement in Question No. 3 to test the division expression in the program.

Answer: An assert statement in Python is used to test an expression in the program code. If the result after testing
comes false, then the exception is raised. This statement is generally used in the beginning of the function or after
a function call to check for valid input.

The syntax for assert statement is: assert Expression[,arguments]

On encountering an assert statement, Python evaluates the expression given immediately after the assert keyword. If this expression is false, an AssertionError exception is raised which can be handled like any other exception.

 n = int(input("Enter Number 1 :"))
 m = int(input("Enter Number 2 : "))
 assert (m == 0), "Oops , Zero Division Error ...."
 print("Quotient : ", n / m) 

Output -1 :

Enter Number 1 :10
Enter Number 2 : 2
Traceback (most recent call last):
File “D:/PythonProg/ExceptionHandling/DivideByZero.py”, line 4, in
assert (m == 0), “Opps, …. ZeroDivisionError”
AssertionError: Opps, …. ZeroDivisionError

Output – 2:

Enter Number 1 :10
Enter Number 2 : 0
Traceback (most recent call last):
File “D:/PythonProg/ExceptionHandling/DivideByZero.py”, line 5, in
print(“Quotient : “, n / m)
ZeroDivisionError: division by zero

5. Define the following:
a) Exception Handling
b) Throwing an exception
c) Catching an exception

Answer:

(a) Exception Handling: Writing additional code in a program to give proper messages or instructions to the user on encountering an exception, called exception handling.

try:
   statements
except Exception_Name:
   statements for handling exception

(b) Throwing an Exception : Throwing an exception means raising an exception.

Each time an error is detected in a program, the Python interpreter raises (throws) an exception. Exception handlers are designed to execute when a specific exception is raised.

Programmers can also forcefully raise exceptions in a program using the raise and assert statements. Once an exception is raised, no further statement in the current block of code is executed.

raise NameError
assert conditon, "message"

(c) Catching an exception : Catching an exception means handling of an exception by exception handlers. An exception is said to be caught when a code that is designed to handle a particular exception is executed. Exceptions, if any, are caught in the try block and handled in the except block.

try:
   statements
except Exception_Name:
   statements for handling exception

6. Explain catching exceptions using try and except block.

Answer : An exception is said to be caught when a code that is designed to handle a particular exception is executed. Exceptions, if any, are caught in the try block and handled in the except block.

While writing or debugging a program, a user might doubt an exception to occur in a particular part of the code. Such suspicious lines of codes are put inside a try block. Every try
block is followed by an except block. The appropriate code to handle each of the possible exceptions (in the code inside the try block) are written inside the except clause.

While executing the program, if an exception is encountered, further execution of the code inside the try block is stopped and the control is transferred to the except block.

 print ("Practicing for try block")
 try:
   numerator=50
   denom=int(input("Enter the denominator"))
   quotient=(numerator/denom)
   print ("Division performed successfully")
 except ZeroDivisionError:
   print ("Denominator as ZERO…. not allowed")
 print(“OUTSIDE try..except block”)

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:

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")
finally : # to be executed at the end
print(" JOB OVER… GO GET SOME REST")

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:

Code to show the wrong number of arguments with exception handling.

 import math
 try:
     print(math.sqrt(25,6))
 except TypeError:
     print("Wrong number of arguments used in sqrt() ")
 finally:
     print("Okay, Correct it")

Output:

Wrong number of arguments used in sqrt()
Okay, Correct it

9. What is the use of finally clause? Use finally clause in the problem given in Question No. 7.

Answer: The try statement in Python can also have an optional finally clause. The statements inside the finally block are always executed regardless of whether an exception
has occurred in the try block or not. It is a common practice to use finally clause while working with files to ensure that the file object is closed. If used, finally should always be placed at the end of try clause, after all except blocks and the else block.

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")
finally : # to be executed at the end
print(" JOB OVER… GO GET SOME REST")


Class 12 NCERT Solution – Computer Science



Class 11 NCERT Solution – Computer Science



Class 12 NCERT Solution – Informatics Practices



Class 11 NCERT Solution – Informatics Practices



Leave a Comment

You cannot copy content of this page

Scroll to Top