KEMBAR78
Chapter 6 - Exception Handling | PDF | Control Flow | Python (Programming Language)
0% found this document useful (0 votes)
19 views18 pages

Chapter 6 - Exception Handling

This chapter covers exception handling in Python, explaining the types of errors (compile-time and run-time) and the mechanisms for managing them. It introduces concepts such as try-except blocks, the importance of separating error-handling code, and built-in exceptions. Additionally, it provides examples of how to implement exception handling to create robust and fault-tolerant programs.

Uploaded by

tehreembasheer1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views18 pages

Chapter 6 - Exception Handling

This chapter covers exception handling in Python, explaining the types of errors (compile-time and run-time) and the mechanisms for managing them. It introduces concepts such as try-except blocks, the importance of separating error-handling code, and built-in exceptions. Additionally, it provides examples of how to implement exception handling to create robust and fault-tolerant programs.

Uploaded by

tehreembasheer1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Exception Handling

C h a pt e r
6
In This Chapter
6.1 Introduction
6.3 Concept of
6.2 Exceptions and Exceptiorn Handling
Exception Handling 6.4 Exception Handling in Python

6.1 Introduction
When you create and develop programs, errors occur naturally. Sometimes, you misspell a
very
name or keyword, or sometimes you unknowingly change the symbols. These are not that
easy and errors are
Common and easy to handle errors. But programming is not that
language developers have
Simple. So, to handle virtually any type of errors that may occur,
Python also supports a specific and
Created numerous ways to catch and prevent them.
errors of any type that may occur. This
well-defined mechanism of catching and preventing
nechanism is known as Exception Handling. In
this chapter you are going to learn about
techniques in Python, different types of errors that may occur and ways to
GACePion handling
avoid them.

265
Chapter
COMPUTER SCIENCE WITH
266 PYTHON - XIl

6.2 Exceptions and Exception Handling


Exception, in general, refers to some contradictory or
unexpected situation or in short, an error
development, there may be some cases
wha
unexpected. During program
that is that this code-fragment
programmer does not have the certainty ExCEPTION
it accesses to resourcesthat
because
is going to work right,either unexpected range, etc.
Contradictory or Unexpected
out of an situation or unexpected error. 6.3
do not exist or because it gets called exceptions during program execution, is
generally
These types of anomalous situations are exception handling. known as Exception.
and the way to handle them is called
Broadly there are tuo types of errors :
resulting out of violation of programi
(i) Compile-time errors. These are the errors
syntactically incorrect statement like:
language's grammar rules e.g., writing
print ("A" + 2)
syntax errors aro
will result into compile-type error because of invalid syntax. All
reported during compilation.
situations.
(ii) Run-time errors. The errors that oCcur during runtime because of unexpected Exception
Such errors are handled through exception handling routines of Python.
handling is a transparent and nice way to handle program errors.
exception
Many reasons support the use of exception handling. In other words, advantages of
handling are :
code.
(i) Exception handling separates error-handling code from normal
(i) It clarifies the code (by removing error-handling code from main line of program) and
enhances readability.
(iii) It stimulates consequences as the error-handling takes place at one place and in one
manner.

(iv) It makes for clear, robust, fault-tolerant programs.


So we can summarize Exception as :
It is an exceptional event that occurs during runtime and causes normal program flow to be disrupteu.
Some common examples of Exceptions are:
> Divide by zero errors
> Acessing the elements of an array beyond its range
> Invalid input
> Hard disk crash
ExCEPTION HANDLING
> Opening a non-existent file anomalous
Whe
Way of handling
> Heap memory exhausted situations in a program-run,
Handling.
For instance, consider the following code : known as Exception

>>>print (3/0)
If you execute above code, youll receive an error message as:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
print 3/0
ZeroDivisionError: integer division or modulo by zero Unh
Chapter 6: EXCEPTION HANDLING
267
This message 1s generated by default
handler does the following upon exception handler of Python. The default
occurrence of an
exception
(i) Prints out exception Exception :
(ii) Prints the stack trace,description
ie., hierarchy of methods where the
(iii) Causes the program to exception occurred
terminate.
6.3 Concept of Exception Handling
The global concept of error-handling is pretty
simple. That is, write your code in such a way
that it raises some error flag every time something
goes wrong. Then trap this error flag and if
this is spotted, call the error handling routine. The intended
like the one shown in Fig. 6.1.
program flow should be somewhat
The raising of imaginary
error flag is called throwing 3
or raising an errTOr. When an Write code
. Such that it Gall
error is thrown, the overall raises an 2| the
error-flag every If error flag Error
system responds by catching time something handiing
the error. And surrounding a goes wrong
is raised then routine

block of error-sensitive
throw exception catch eXception
code-with-exception-handling
is called trying to execute a
Figure 6.1 Concept of exception handling.
block.
Some terminology used within exception handling follows.
Description Python Terminology
An unexpected error that occurs during runtime Exception
A set of code that might have an exception thrown in it. try block
The process by which an exception is generated and passed Throwing or raising an error
to the program.
Capturing an exception that has just occurred and executing Catching
statements that try to resolve the problem
The block of code that attempts to deal with the exception except clause or exceptlexception
block or catch block
(ie., problem).
Stack trace
The sequence of method calls that brought control to the
point where the exception occurred.

When to Use Exception Handling


NoTE
The exception handling is ideal for: An exception can be generated
processing exceptional situations. by an error in your program, or
components that cannot explicitly via a raise statement.
processing exceptions for
handle them directly.
error-processing.
> large projects that require uniform

NoTE
Unhandled exceptions will cause Python to halt
execution.
COMPUTER SCIENCE
WITH
268 pUIHON
Handling in Python
6.4 Exception and except clauses in the
wherein the
Exception code that
Handling in

whenthe
Python involves the
use of try

exception is raised, is written in except block.


fol owinglorna
may generate an exception is written in the try block and the code tox

handling exception

See below:

try: generate an exception


thwrite here the code that may
except :
thwrite code here about what to do when the exception has occurred

following code:
For instance, consider the
try :

print ("result of 10/5 =", (10/5) )


print ("result of 10/0 =", (10/0)) The code that may raise an
exception is written in try block
This is exception except :
block : this will
execute when the
exception is raised print ("Divide by Zero Error! Denominator must not be zero!")

The output produced by above code is as shown below :


result of 10 / 5 = 2
result of 10 / 0 = Divide by Zero Error! Denominator must not be zero!

See, the expression (10/0) raised exception


which is then handled by except block
See, now the output produced does not show the scary red-coloured standard error message ;
is now showing what you defined under the exception block.
Consider another code that handles an exception raised whenacode tries
to a number: conversion tron eA

try:
X= int ("XII")
except:
print ("Error converting 'XII toa
number")
The output generated from above
code is not the usual error now, it
is :
Error converting 'XII' to a number

Consider program 6.1 that is expanded version of the above example. It terror-checks auser's
input to make sure an
integer is entered.
HANDLING
269
EXCEPTION

Chopter6

Write a program to ensure that an integer is entered as input


6.1 and in case any other value 1S enteleu, .
displays a message- Not a valid integer'
r o g r a m
ok = False
while not ok :
try :
numberString = input ("Enter an integer:")
n= int(numberString)
ok = True
except :
print ("Error! Not a valid integer.")
integer: oo7
Enter an
integer.
Error! NOt a valid
integer: 007
Enter an

6.4.1
General Built-in Python Exceptions
In this section, we are discussing about some built-in exceptions of Python. The built-in
exceptions can be generated by the interpreter or built-in functions. Some common built-in
exceptions in Python are being listed below in Table 6.1.
able 6.1 Some built-in Exceptions

Exception Name Description


EOFError Raised when one of the built-in functions (input( ) hits an end-of-file condition (EOF)
without reading any data. (NOTE. the file.read( )and file.readline( ) methods return an
empty string when they hit EOF.)
IO Error Raised when an I/O operation (such as a print statement, the built-in open( )function
or a method of a file object) fails for an I/0-related reason, e.g., "file not found" or "disk
full".
NameError Raised when a local or global name is notfound. This applies only toungqualified names.
The associated value is an error message that includes the name that could not be found.
IndexError Raised wh¹n a sequence subscript is out of range, e.8., from a list of length 4 if you try
to read avalue of index like 8 or -8 etc. (Slice indices are silently truncated to fall in the
allowed range; if an index is not a plain integer, TypeError is raised.)
ImportError Raised when an import statement fails to find the module definition or whern a from ...
import fails to find a name that is to be imported.
TypeError Raised when an operation or function is applied to an object of inappropriate type, e.g.,
if you try to compute a square-root of a string value. The associated value is a string
giving details about the type mismatch.
ValueError Raised when a built-in operation or function receives an argument that has the right
type but an inappropriate value, and the situation is not described by a more precise
exception such as lndexError.
ZeroDivisionError Raised when the second argument of a division or modulo operation is zero.
OverflowError Raised when the result of an arithmetic operation is too large to be represented.
KeyError Raised when a mapping (dictionary) key is not found in the set of existing keys
ImportError Raised when the module given with import statement is not found.
KeyboardInter upt Raised when keys Esc, Del or Ctrl+C ispressed during program execution and normal
programn flow gets disturbed.
COMPUTER SCIENCE WITH
270
PrTHON
may occur whle opening a file.
Following program 6.2 handles an error that

6.2 Program to handle exception while opening a file.


try:
Irogram
my_file = open("myfile.txt", "r")
print (my_file.read())

except:
print ("Error opening file")

The above program will open the file successfully if the file Error opening file
myfile.trt exists and contains some data otherwise it shows an
output as :

Now the above output may be of one of the wo reasons :


(i) the file did not exist or (ii) there was no data in the file.

But the above code did not tell which caused the error.

6.4.2 Second Argument of the except Block


You can also provide asecond argument for the exceptblock, which gives a reference in h
exception object. You can do it in following format:
try:
# code
except <ExceptionName> as <exArgument> :
# handle error here

The except clause can then use this additional argument to print the associated error-message of
this exception as : str (exArgument). Following code illustrates it :
try:
print ("result of 10/5 =", (10/5) )
print ("result of 10/0 =", (10/0) ) Notice second argument to except block i.e., e
except ZeroDivisionError as e: here - gets reference of raised exception
print ("Exception ", str(e)) Printing standard error message of raised
exception through the second argument
The above code will give output as:
result of 10/5 = 2.0
EXception - division by zero The mesage associated with the exception

6.4.3 Handling Multiple Erors


Multipletypes of errors may be captured and processed differently. It tcan be usefulI to provid a
more exact error message to the user than a simple "an error has occurred." In order to capture
and process different type of exceptions, there must be multiple exception blocks - each one

pertaining to different type of exception.


ó
EXCEPTION HANDLING
Chopler

ie is done as per tollowing format 271

try:
#:

except <exceptionName1> :
#:

except <exceptionName2> :
#:
except : The except block without any
will handle the
rest of the exception nam
exceptions
else :
*Tfthere is no
exceptionthen the statements in this
block get executed.
kolso :clause willexecute if
there is no
Vou want to
execute when
no exceptions get exception raised, so you may put your code that
raised. Following programn6.3 illustrates the same.
6.3 Program to handle multiple exceptions.
try:
Irogram
my_file =open("myfile.txt")
my_ line =my_file.readline()
my_int = int(s.strip() )
my_calculated_value = 101/my_ int
except IOError: These three except blocks will catch and
handle tOError, ValueError and
print ("I/0 error occurred") ZeroDivisionError exceptions respectivety
except ValueError:
print ("Could not convert datato an integer.")
except ZeroDivisionError : +
print ("Division by zero error")
except: The unnamed except block will
handle the rest of the exceptions
print ("Unexpected error:")
else :
print ("Hurray! No exceptions !") This last else: block will get executed
if no exception is raised
The output produced by above code is :
I/0 error occurred

Exception Hondling execution orde NoTE


The named except: blocks handle
The <try suite> is executed first; the named exceptions while the
the <try suite>,
an
if, during the Course of executing
handled otherwise,
and
unnamed except: block handles
all other exceptions - exceptions
exception is raised that is not
with <name>
bound to the not mentioned in named except:
the except then
suite> is executed, except suite
is found blocks.
exception,
if found; if no matching
unnamed except suite is executed.
SCIENCE WITH

272
You can alsouse
finally afinally: block along
Block with a try: block, just like you use except: Jlock,eg,%,
6.4.4 The

exception
try:
statements that may raise
#
[except:
exception here]
# handle
finally: run
that will always
# statements block is that:
between an except: block and the finally: the finally: block
The difference
that contains any code that must execute, whether the try: block raised an exception or n
isaplats.
For example,
try:
"r+")
fh =open("poems. txt", This statement will always be
fh.write("Adding new line") executed in the end

finally:
data")
print ("Error: can\'t find file or read
You may combine finally: with except: clause. In such a combination, the except: block will ge
executed only in case an exception is raised and finally: block will get executed ALWAYS,0n
the end. Following code illustrates it:
try:
fh =open("poem1.txt", "r")
print (fh. read())
except:
print ("Exception Occurred")
finally:
print ("Finally saying goodbye.")
The output produced by above code will be :
Exception Occurred This is printed because except: block
This is printed because got executed when exception occurred.
finally: block got executed
in the end. Finally saying goodbye
In the above code if no exception is raised, still the above
code will print :
Finally saying goodbye
because finally : block gets executed always in the
end.
6.4.5 Raising/Forcing an Exception
In Python, you can use the raise
keyword to raise/force an exception. That
programmer can force an exception meo
message to your exception handling tomodule.
occur through raise keyword. It can also pass
raise <exception> (<message>) For example:
The exception raised in this way should be apre-defined Built-in exception. Consider following
code snippet that forces a ZeroDivisionError exception to occur without actually dividing&
value by zero :
EXCEPTION HANDLING

try:
273
a= int(input ("Enter numerator :")) Notice this raise
b= int (input ("Enter built-in exception statement is raising

ifb ==0:
denominator :") ZeroDivisionError
with a custom message,
that followS
the exception name
naise
ZeroDivisionError (str(a) +"/0 not
print (a/b)
possible")
except ZeroDivisionError as e:
print ("Exception", str(e))
The output produced by above code is :
Enter n u m e r a t o r : 7

Fnter denominator :0 This was the


EXception 7/0 not possible as str(e) custom-message
because the exceptionsent: printed
reference was received in e
Puthon assert Statement

In some you have a clear idea about


situations.
the requirements and
conditions and where results test-conditions
know the likely resuts of some required. So in programs
mch the programs, you can use being different from the expected
Python assert statement if the condition results
Drhon's assert statement is a debuggng aid is resulting as expected or not.
that tests a condition. If the condition is
Nr nrogram just continues to true, it does nothing and
execute. But if the assert condition
AssertionError exception with an optional error evaluates to false, it raises an
message. The syntax of assert statement in
assert condition [, error_message ] Python, is :
For example, consider the following code : Specify the optional, custom message
through error message
print("Eter the Numerator: ")
n=int (input()) Custom Error message
specified
print("Enter the Denominator: ") NoTE
d= int(input() ) This error message will be The assert keyword in Python
assert d!=0, "Denominator must not be 0" conditiononlyd !=
printed when the given
0 results
is used when we need to
detect problems early.
print("n/d =", int (n/d) ) into false.

Benefits of Exception Handling


Exception provides the means to separate the details of what
C h e c k
P o i n t

6.1 to do when something out of the ordinary happens from the


1 Nane the
block that encloses the code main logicof a program. In short, the advantages of exception
uat may encounter anomalous
situations.
handling are :
2 In
which block can you raise the () Exception handling separates error-handling code from
3.
exception ? normal code.
Which block traps and handles an (ii) It clarifies the code and enhances readability.
exception ? (iii) It stimulates consequences as the error-handling takes
One
ind except block sufficiently trap place at one place and in one manner.
handle multiple exceptions ? (iv) It makes for clear, robust, NoTE
block exception
Miat er which is always executed no fault-tolerant programs.
All exceptions are sub-classes
Hame the raised ?
of Exception class.
TOot class for all exceptions.
COMPUTER SCIENCE WITH
274

LET US REVISE

anomalous situations in
a program.run is
known as exception handling.
Way of handling take place.
enclosing the code wherein exceptions can
The try block is for handles it.
The except block traps the exception and
4
exception.
The raise keyword forces an
of Exceptionclass.
All exceptions are subclasses

OBJECTIVE TYPE QUESTIONS


OTOS
MULTIPLE CHOICE QUESTIONS
1. Errors resulting out of violation of programming language's grammar rules are known as
(a) Compile time error (b) Logical error
(c) Runtime error (d) Exception
2 Anunexpected event that occurs during runtime and causes program disruption, is calla
(a) Compile time error (b) Logical error
(c) Runtime error (a) Exception
3. Which of the following keywords are not specific to exception handling?
(a) try (6) except (c) finally (d) else
4. Which of the following blocks is a 'must-execute block ?
(a) try (6) except (c) finally (d) else
5. Which keyword is used to force an exception?
(a) try (6) except (c) raise (d) finally
6. If my_dict is a dictionary as defined below, then which of the following statements will raise a
exception ? [CBSE SP 0243
my_dict =('apple': 10, 'banana': 20, 'orange': 30}
(a) my_dict.get('orange') (6) print (my_dict['apple', 'banana'1)
(c) my_dict['apple']=20
(d) print (str (my_dict))
FILL IN THE BLANKS
1. EOFError
exception is raised when input( ) hits an EOF
2NamError without reading any ata.
exception when a local or global name is
3 TypeError not found.
exception is raised when an operation is
4. When denominator applied to an object of wrong "yr
of a division
5. While accessing a expression is zero,ZeroDivisionError
exception is raised.
dictionary,
6. The code which might
if the given key is not
found, KeyError exception is raised.
raise an exception is kept in try
block.

1. Exception and error are the


TRUE/FALSE QUESTIONS
2. All types of same. False
errors can be found
during compile time. False
6:EXCEPTION HANDLING

275
running properly put
producing
condition occurring during wrong output is an exception. False
program

A rare
Unexpected

runtime which disrupts a


exception. True program's execution is an
deals with the exception, if
block
except it occurs, True
finally is the correct order of
except, blocks in exception
handling.
Anexception may be raised even if the program is syntactically correct. True

in Python, name of the True [CBSE SP 2023-24]


handling exceptions
While
except c l a u s e . False
exception has to be compulsorily added with
finally block in Python is executed [CBSE D 24]
only if no exception occurs
9 The
in the try block. False
[CBSE SP 2024-25]
AsSERTIONS AND REASONS
R E C T I O N S

following question, a statement of assertion (A) is followed by a


choiceas : statement of reason (R).
Mark the correct
(a) Both Aand R are true and Ris the correct explanation of A.
a Both A and R are true but R is not the correct
explanation of A.
iA Ais true but R is false (or partly true).
(0 Ais false (or partly true) but R is true.
ie Both A and R are false or not fully true.

Asertion. Exception handling is responsible for handling anomalous situations during the
execution of a program.
(c)
Reason. Exception handling handles all types of errors and exceptions.
2Asertion. Exception handling code is separate from normal code. (a)
Keason. Program logic is different while exception handling code uses specific keywords to handle
exceptions.
. Assertion. Exception handling code is clear and block based in Python. (a)
Keason. The code where unexpected runtime exception may occur is separate from the codewhere
the action takes place when an exception occurs.
eruon. No matter what exception occurs, you can always make sure that some common action
takes place for all types of
exceptions. (a)
Reason. The finally block Contains the code that must execute.
NOTE :
Answers for 0T0s are given at the end of the book.
Slhed Prohlem
1,
What is an
Exception ?
Solution. Exception in general refers to some contradictory or unusual situation which can be
encountered while executing a program.
COMPUTER SCIENCE \WITH
276
Handling required ?
2 When is Exception handling is ideal
for :
exception
Solution. The
processing exceptional situations
components that cannot
handle
them directly
exceptions for that should not process
processing components
" for widely used
processing exceptions
exceptions error-processing.

that require uniform


large projects
Where does it appear in
exrception handling ? a
What is theAnfunction
Solution. except block in program?
except: ofblock is a group of Python statementsthat are used to handle a raised excephon
3.
placed after each
try: block.
should be
The except: blocks
?
of exception handling
4. iWhat are thc advantages
exception handling are :
Solution. Advantages of code from normal code
separates error-handling
() Exception handling
enhances readability.
() It clarifies the code and
(ii) It stimulates consequences as the error-handling takes place at one place and in one manner
fault-tolerant programs.
(to) It mkes for clear, robust,
5 When do you need multiple except handlers
- exception catching blocks ?
Solution. Sometimes program has more than one condition to throw exceptions. In: such caseS, OTe
blocks with a try block.
can associate more than one except

6. What is the output produced by following code, if the input given is :


(a) 6 (b) 0 (c) 6.7 (d) "a"

try:
x= float (input ("Your number:"))
inverse =1.0/x
except ValueError:
print ("You should have given either an int or a float")
except ZeroDivisionError:
print ("Infinity")
finally:
print ("There may or may not have been an exception. ")
Solution.
(a) There may or may not have been an exception.
(b) Infinity
There may or may not have been an exception.
(c) There mayor may not have been an exception.
(d) Youshould have given either an int or a float
There may or may not have been an exception.
7. What is the purpose of the finally clause of a
try-catch-finally statement ? whetheren

Solution. The finally clause is used to provide the capability to Code no


matter w
an exception is thrown or caught. execute
EXCEPTION HANDLING 277

the codes and inputs given below :


the
l d e n t i h y
type of exceptionfor
#input as "K"
(b) for ain range (0, 9):
int (input (""Please enter a number ;"))
(a)
X= print (20/a)

) import mymodule

) x=8 (e) mylist - [2, 3, 4]


print (X) print (mylist [4])

9 import math (&) filename - "great . txt"


pow(109000, 100000) open("graet. txt", "r")
a= math.
Solution. (a) V a l u e E r r o r (b) ZeroDivisionError (c) ImportError (d) NameError
(c) IndexError () OverflowError (&) IOError

Predict thc output of the following


code for these function calls:
(a) divide(2, 1) (b) divide(2, 0) (c) divide("2","1")
def divide (x, y) :
try:
result = x/y
except ZeroDivisionError:

print ("division by zero!")


else:

print ("result is ", result)


finally:
print ("executing finally clause" )
Solution.
result is 2
la, divide(2, 1)
executing finally clause

(b) divide(2, 0) division by zero!


executing finally clause

() divide("2", "1")
executing finally clause
Traceback (most recent call last):
line 1, in <module>
File "<pyshell#46>",
divide("2", "1")
divide
File "C:/test16..py", line 22, in
result= X/y 'str' and'str'
type(s) for/:
TypeError: unsupported operrand
COMPUTER
SCIENCE
278 MITH
PrTHOH
GUIDELINES TO NCERT
QUESTIONS

Python
NCERT
1: Exception Hondling in
NCERT Chapter be a syntar
error is an cxception but
every exception
cannot error."
Justify the
1. "Every syntax
means occurrence of some
unexpected Syntaxevent.
error occurs Sateme
hence can be
Ans. An exception is unexpected event and termed
violated, which
language rules are unexpected event causing
However,exception means occurrence of
time only.
program
syntax errors are caught during compile
runtime, while every exception cannot be a
"every syntax error is an exception but syntax erro0r."
Hence to
exceplions raised ? Give
examples support your ansuwers.
2. hen are the tollowing buill-in (c) NameError (d) ZeroDivisionError
(b) IOError
(a) ImportError
examples of these
Ans. For exception details,
refer to Table 6.1. For exceptions
:
(a) Refer to Q. 8(c)
(b) Refer to Q. 8(g)
(c) Refer to Q. 8/d)
(d) Refer to Q.8(b)
numbers
3. What is the usc of a raise statement ? Write a code to accept two and display the
Appropriate exception should be raised if the user enters the second number (denominator) ootn
Ans.
The raise keyword is used to manually raise arn exception like exceptions are raised hr Bd
itself.
a = int( input("Enter value for a :"))
b= int( input("Enter value for b :"))
try:
if b == 0:
raise ZeroDivisionError # raising exception using raise keyword
print (a/b)
except ZeroDivisionError:
print("Please enter non-zero value for b. ")
4. Use assert statement in Question No. 3 to test the
division expression in the progrul.
Ans.
a= int(input("Enter value for a
:"))
b= int(input("Enter value for
b:"))
assert b!=0, "Value for b must
be non-zero"
print(a/b)
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"))
EXCEPTION HANDLING
279
quotient= (hum1/num2)

the numbers entered were


p r i n t ( " B o t h

correct")
# toenter only integers
print(""Please enter only numbers")
e x c e p t

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

else:

print(
"Great you are a good programmer")
# to be éxecuted at the end
print("JOB OVER... GO GET SOME REST")

Ans.

print ("Learning Exceptions...")


try:
numi =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 agood programmer")
finally: # to be executed at the end
print("JOB OVER... GO GET SOME REST")

XI. Write a code where you use the wrong number of


&. You have learnt how to use math module in Class ValueError
the exception handling process to catch the
arguments for amethod (say sqrt( ) or pow( )). Use
exception.
Ans.

import math
print ("Code to test wrong TYPE of arguments")
try:
number"))
numl = int (input ("Enter the first
result1 =math.sqrt(num1)
print ("Sqrt:", result1) integers
except ValueError: # to enter only

Prant ("Please enter only Positive numbers)


try: number"))
num2 =in the second
int (input("Enter
result2 =math.pow(num1, num2)
COMPUTER SCIENCE
280
print ("POw:", result2)
# to enter only integers
except Value£rror:

numbers")
enter only
print ("Please
t tobe executed at the end
finally:
types; Wrong no, of requires requires
print ("Tested only wrong *
args")
of arquments
Code to test wrong TYPE
number-9
Enter the first
Positive numbers
Please enter only
numberk
Enter the second
Please enter only numbers
requires *aras
Tested only wrong types; Wrong no. of requires
Code to test wrong TYPE of arquments
Enter the first number6
Sgrt: 2.449489742783178
Enter the second number4
POw: 1296.0
Tested only wrong types; Wrong no. of requires requires *args

9. What is the use of finally clause ? Use finally clause in the problem given in
Question No
Ans. Refer to section 6.4.4.

GLOSSARY
Exception An onomalous situation encountered by
the program.
Syntax error Programming language's grammar rules violation error.
Compile time errorError that the compiler/interpreter
Run time error
can find during compilation.
Error during program execution.

Assisnment
1. What is exception ?
What is exception handling ?
2. Why is exception
3. How do you raise handling necessary ?
an exception? Give
4. How do you code example.
handle an exception in
5. Describe the Python ?
keyword try. What is the
6. Predict the
output by following code : role of try block?
import math
def f(x):
if x<=0:
raise ValueError(f: argument
must be greater
return math.sqrt(x)+2than zero)
:EXCEPTION HANDLING
281
d e f g ( x ) :

y=f(x)

print (y >2)

try:

g(1)

g(-1)
except Exception, e:
print Exception', e.message

Which of the following two codes will print "File does not exist"
ifthe file being opened does not exiSt
if filename != " ":
() (b) try:
f= open(filename, 'r)
f=open(filename, ')
else:
except IOError:
print ("file does not exist") print ("file does not exist")
8IWhich of the following four outputs is produced by the code that follows ?
output 1:
-2 -1
-1 -1
0integer division or modulo by zero

output 2 :
-2 -1
-1 -1
0integer division or modulo by zero
11
20

output 3 : output 4 :
-2 -2 -1
-0.5 -1 -1 -1
-1.0 0 0 Exception occurred
division by zero

1.0 2
0.5

Given code is :
for x in range(-2, 3) :
print (x, sep =""),
try:
print (1/x, end =" ")
except ZeroDivisionError as e :
print (str(e) )
except :
print ("Exception occurred")
COMPUTER SCIENCE WITH
282
PYIHON -
following code fragments
:
9 Find the errors in
(a) try:
fs = open ("/notthere")
exception IOError: gracefully")
print ("The file does
not exist,exiting
always print")
print ("This line will

(b) try:
fh = open("abc. txt")
try:
fhl = open ("newl.txt", "r")
except ValueError:
gracefully")
print ("The file does not exist, exiting
(c) def ret ():
sqrs = [ x**2 for x in range(1, 10) ]
i =0
w.ile True :
return sqrs[i]
i+=1
c= ret().next()
10. Write a function read a Time class object storing hours and minutes. Raise a user-defined error if values
other than 0..23 is entered for hours and other than 0.59 is entered for minutes.
11. Write a program to read details of student for result
preparation.
exception-handling codes such as ValueError, IndexError, ZeroDivisionError,Incorporate all possible
user-defined exceptions
etc.

You might also like