NCERT Solutions Class 12, Computer Science, Chapter- 1, Exception Handling in Python
Exercise
1. “Every syntax error is an exception but every exception cannot be a syntax error.” Justify the statement.
Solution:
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
Solution:
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
Solution:
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
Solution:
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
Solution:
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).
Solution:
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.
Solution:
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
Solution:
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
Solution:
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
Solution:
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.
Solution:
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")
Solution:
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.
Solution:
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