Exception Handling
In This Chapter
6.1 Introduction 63 Concept of
6.2 Exceptions and Exception Handling
Exception Handling
6.4 Exception Handling in Python
eee
|
|
pa Introduction
[)When you create and develop programs, errors occur naturally. Sometimes,
name or keyword, or sometimes you unknowingly change the symbols.
common and easy to handle errors. But programming is not that easy and «
simple. So, to handle virtually any type of errors that may occur,
created numerous ways to catch and prevent them. Python al
well-defined mechanism of catching and preventing errors of ant
mechanism is known as Exception Handling. In this chapter y
|| exception handling techniques in Python,
avoid them.
you misspell a
These are very
‘rrors are not that
language developers have
iso supports a specific and
y type that may occur. This
ou are going to lea about
different types of errors that may occur and ways toy
COMPUTER SCIENCE
260 WITH Py
on
6.2. Exceptions and Exception Handling
Exception, in general, refers to some contradliclory Of umexpected station oF inch
, " '
that is unexpected. During program development, there may be some cases #2,
he certainty that this code-fragment eH
ammer does not have t
programmer do r
is goin 7 jther because it accesses to resources that
is going to work right, either b i : !
‘ >, etc.
do not exist or because it gets out of an ears ange 6 situation or ung
“These types of anomalous situations are generally < led exceptions during progam et!
and the way to handle them is called exception handling. known as Exception. 4
Texcerrion
Broadly there are fwo types of errors +
(i) Compile-time errors. These are the errors resulting out of violation of program
language’s grammar rules eg., writing syntactically incorrect statement like : ming
print ("A" +2)
will result into compile-type error because of invalid syntax. All syntax errors
reported during compilation. e
(ii) Run-time errors. The errors that occur during runtime because of unexpected situatoy
Such errors are handled through exception handling routines of Python. Excepin
handling is a transparent and nice way to handle program errors.
Many reasons support the use of exception handling. In other words, advantages of excepia
handling are :
( Exception handling separates error-handling code from normal code.
(ii) It clarifies the code (by removing error-handling code from main line of program) ai
enhances readability.
(iii) It stimulates consequences as the error-handling takes place at one place and ine
manner.
(jv) 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: disrupted
Some common examples of Exceptions are :
© Divide by zero errors
© Accessing the elements of an array beyond its range
© Invalid input
© Hard disk crash
: uN
© Opening a non-existent file Dexcertion Hien
Way of handing 20%
tuations in 2 progam
situations in 2 Peg
© Heap memory exhausted
For instance, consider the following code : known as Excert
>>> print (3/8)
If you execute above code, you'll receive an error message as :
Traceback (most recent call last):
File "
", line 1, in
print 3/0
ZeroDivisionError: integer division or modulo by zero4 BCEPTION HANDLING
is message is generated by default exce
This message is generat “xception handler of Python. The default exception
handler does the following upon occurrence of an Bxception .
(p Prints out exception description
(i) Prints the stack trace, i., hicrarch
(ii) Causes the program to terminate,
63 concel it of Exception Handlin,
The global concept of error-handling is pretty simple. That i,
that it raises some error flag every time somethi
this is spotted, call the error handlin,
like the one shown in Fig, 6.1.
'Y of methods where the exception occurred
The raising of imaginary
error flag is called throwing 7
ortaising an error. When an Wit code
emror is thrown, the overall ‘amen | ca
system responds by catching 19 ory Hevertg || Sra
the error. And surrounding a goes wrong” Is reised then routine
block of _ error-sensitive- [row econ] GROSS
code-with-exception-handling
is ring to execu
is led tying to execute a Figure 61. Concept of exception handing,
Jock.
Some terminology used within exception handling follows.
Description
Python Terminology __|
| An unexpected error that occurs during rantime
|
Exception
| Aset 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
| ie, problem). block or catch block
The sequence of method calls that brought control to the | Stack trace
int where the exception occurred.
When to Use Exception Handling
‘The exception handling is ideal for :
© processing exceptional situations. pocepe tint icet bel exnersted
by an error in your program, or
® Processing exceptions for components that cannot explicitly via a raise statement.
handle them directly.
® large projects that require uniform error-processing.
Uae
Nore
Uns
wet exceptions wil cause Python to halt execution.262
COMPUTER SCIENCE wre
1
F et Pry
6.4 Exception Handling in Python oH
Exception Handling in Python involves the use of try and except pt clauses in
wherein the code that may generate an exception is wrillen in.the try | yl ing
handling exception when the exception is raised, is written in except blot’ 4 ther"
See below :
ary:
#write here the code that may generate an exception
_except ¢
thurdite code here about what to do when the exception has occy
Irred
For instance, consider the following code :
try:
print (“result of 10/5 =", (10/5))
print (“result of 10/0 =", (10/@)) SG The code that may race ax
exception is writen nt Ba
This is exception except +
block ; this will a
execute when the 5
‘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!
“SS
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 messi
is now showing what you defined under the exception block.
Consider another code that handles an exception raised when a code tries conversion froma
to a number :
try:
wa = int("xII")
except:
print ("Error converting 'XIT' to a number")
The output generated from above code is not the usual error now, it is :
Error converting ‘XII’ to a number
ust
Consider program 6.1 that is expanded version of the above example. It error- checks *
input to make sure an integer is entered.ser 6 + EXCEPTION HANDLING
263
G1 Writes progam to ensure that an integer is ered .
displays a message ~ ‘Not a valid integer nn MPH and in case any other value fs entered, i
eon ok = False
while not ok :
try:
numberString. = input(“Enter ar
N= int(numberstring)
ok = True
except :
in integer")
Print ("Error! Not a valid integer.")
enter an integer: 007 :
error! Not a valid integer,
enter an integer: 007
General Built-in Python Exceptions
In this section, we are discussing about some built
exceptions can be generated by the interpreter or built-i
exceptions in Python are being listed below in Table 6.1,
Table 6.1 Some built-in Exceptions
exceptions of Python. The b
in functions. Some common bi
Exception Name Description ]
| 2
| E0rEror | 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.) | 7
10 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 1/O-related reason, eg, “file not found” or “disk -
full”.
NameError
Raised when a local or global name is not found. This applies only to unqualified names. |
L
i
| The associated value is an error message that includes the name that could not be found.
| IndexError Raised when a sequence subscript is out of range, e.g, from a list of length 4 if you try
to read a value 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.) 7
1 ImportError Raised when an import statement fails to find the module definition or when a from .
| import fails to find a name that is to be imported.
t
|
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
ving 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 IndexError.
|_ZewDivisionError | Raised when the second argument of a division or modulo operation is zero.
| OverfinwError 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
Import rror Raised when the module given with import statement is not found.
Keyboardinterrupt | Raised when keys Esc, Del or Ctrl+C is pressed during program execution and normal
program flow gets disturbed.264
COMPUTER SCIENCE
with Py
iy
Following program 6.2 handles an error that may occur while opening a ae
ile, \
6.2 Program to handle exception while opening a file.
try:
rogram
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
P ‘ nae el .
myfile.txt exists and contains some data otherwise it shows an TOT opening Fin,
output as :
Now the above output may be of one of the fwvo 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 a second argument for the except block, which gives a reference ty
exception object. You can do it in following format :
try:
# code
except as :
# handle error here
‘The except clause can then use this additional argument to print the associated error-messagedt
this exception as : str (exArgument). Following code illustrates it :
try
print (“result of 10/5 =", (10/5))
print (“result of 18/@=", (10/8)) Notice second argument to except block ie, €
except ZeroDivisionError as @ : <———— l#”# ~ ges reference of raised exception
print (“Exception
3 str(e)) «___— Printing standard error message of raised
‘exception throughs the second argument
The above code will give output as :
result of 10/5 = 2.0 m ered
ertentich eidivistonleyiete = The message associated with the exception
6.4.2. Handling Multiple Errors
z ide?
Multiple types of errors may be captured and processed differently. It can be useful to Prov
more exact error message to the user than a simple “an error has occurred.” In order to capt
one
and process different type of exceptions, there must be multiple exception blocks - €2**
pertaining to different type of exception.265
6; EXCEPTION HANDLING
copter 6 *
is done as per following format :
Thi
try:
a
except :
we
except :
#
The except block without any eee
——__— Pt block without any exception name
excep! will handle the re e
; uate
oe AP
#1F there is no exception then the statements in this block get executed.
The last else: clause will execute if there is no exception raised, so you may put your code that
you want to execute when no exceptions get raised. Following program 6.3 illustrates the same.
6.3 Program to handle multiple exceptions.
try:
eg my_file = open(“myfile.txt")
my_line =my_file.readline()
my_int = int(s.strip())
my_calculated_value = 101 / my_int
‘These three except blocks will catch and
handle 1OError , ValueError and
ZeroDivisionError exceptions respectively
except I0Error:
print (“1/0 error occurred")
except Valuetrror:
print ("Could not convert data to an integer.")
except ZeroDivisionError:
print ("Division by zero error")
except: ‘The unnamed except block will
print (“Unexpected error:") <————__ handle the rest ofthe exceptions
else :
Prdnt (“Murray! No exceptions!") «sa. ia ete: block wil get executed
If no exception is raised
The output produced by above code i
¥/0 error occurred
Sception Handling — execution order ‘ forte
The , an the named exceptions while the
€xception is raised that is not handled otherwise, and ‘unnamed except: block handles
ae , all other exceptions ~ exceptions
the is executed, with bound to the Se ea ea
“xception, if found ; if no matching except suite is found then beck
unnamed except suite is executed. nL a266
Computer SCIENCE 7
6.4.4 The finally Block H Pie
You can also use a finall
try:
: block along with
a try block ust lke You use egy r
PL log,
be
# statements that may raise exception Boi,
[except:
#handle exception here]
finally:
# statements that will always run
The difference between an except: block and the finally: block i that the final
that contains any code that must execute, whether the try: block raised an Cop
For example, CEP
try:
fh = open("poens.txt", "r+") ‘he emo
fh.write("Adding new Line") cmaued wae
finally:
print ("Error: can\'t find file or read data") ae
You may combine finally: with except: clause. In such a combination, the except tock yay
executed only in case an exception is raised and finally: block will get executed ALWals;
the end. Following code illustrates it :
try:
h = open("poem.txt”, "r")
print (fh.read())
except:
print (“Exception Occurred")
finally:
print ("Finally saying goodbye.")
The output produced by above code will be :
‘This is printed because exces
Pers ed ben Exception Occurred 4——— gor executed when excep
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 et yo
In Python, you can use the raise keyword to raise/force an exception. soo
programmer can force an exception to occur through raise keyword. It can s
message to your exception handling module. For example :
raise ()
‘The exception raised in this way should be a pre-defined Built-in exception Cony al
i actu
code snippet that forces a ZeroDivisionError exception to occur without
value by zero :| EXCEPTION HANDLING |
chop 6
try? *
; Nate hc ute sateen a
a= int(input ("Enter numerator :*)) Sa ne eet
b=int(input("Enter denominator ha custom nese, that follows
ifbee0: eo
raise ZeroDivisionError(str(a) +"/0 not possible”)
print (a/b)
except ZeroDivisionError ase:
print ("Exception", str(e))
“The output produced by above code is: “s
enter numerator : 7
Enter denoninatar :@ ps’ This was th cusom-mesuge sent pine
«es str(e) because the exepion
Exception 7/@ not possible 5~ reference was receive in €
‘nsome situations, you have a clear idea about the requirements and test-conditions required. So in programs
‘where you know the likely results of some conditions and where results being different from the expected results
cancrash the programs, you can use Python assert statement ifthe condition is resulting as expected or not,
ython’s assert statement is a debugging aid that tests a condition. Ifthe condition is true, it does nothing and
your program just continues to execute, But if the assert condition evaluates to false, it raises an
‘AssertionError exception with an optional error message. The syntax of assert statement in Python, is :
assert condition [, error_message
ane Be) + sca optional custom mesage
For example, consider the following code : trough err message
print("enter the Numerator: ") —
n=int(input()) 4 specific Si Nore —
print("Enter the Denominator: ") snisenr mesage iti Te ser keyword in Python
d= int(input()) ere in tegien 18 used when we need 10
assert d!=0, "Denominator must not be @" condition d != 0 results detect problems early.
print(“n/d =", int(n/d)) inode
Benefits of Exception Handling
oss Exception provides the means to separate the details of what
Yorn. i to do when something out of the ordinary happens from the
| main logic of a program. In short, the advantages of exception
1. Wane the block that encloses the code handling are :
‘that may encounter anomalous situations. .
2a which Mock canyon tee. tha; (2, Exception handling separates cerror-handling code from
exception ? normal code.
3. Which tock tape and handles an| (i) It clarifies the code and enhances readability.
exception ? (ii) Tt stimulates consequences as the error-handling takes
‘ = fee except block sufficiently trap place at one place and in one manner.
A tae aa exceptions ? (jv) It makes for clear, robust,
: lock is always executed no t-tolerant programs.
Matter which exception is raised ? Fa ee All exceptions are sub-classes
‘ of Exception class.
Name the root class for all exceptions.COMPUTER
268 SCIENCE Wy Pn,
hy
LeT Us REVISE :
Woy of handling anomalous situations in a program.run is known as exception handling
‘the ty block i for enclosing the code wherein exceptions cam take place,
The except block traps the exception and handles it
4+ The raise keyword forces an exception.
All exceptions are subclasses of Exception class.
[Ws cern SIN ROULSSUITONNS
i OTQs lay
MULTIPLE CHOICE QUESTIONS ~
1. Errors resulting out of violation of programming language's grammar rules are known ag
(a) Compile time error
(b) Logical error —~
(0) Runtime error
(@) Exception
. An unexpected event that occurs during runtime and causes program disruption, is called
(a) Compile time error
(c) Runtime error
(8) Logical error
(@) Exception
Which of the following keywords are not specific to exception handling ?
(@ ty (®) except () finally (A) else
4. Which of the following blocks is a ‘must-execute’ block ?
(a) try (b) except (c) finally (d) else
5. Which keyword is used to force an exception ?
( ty () except (©) raise (@ finally
FILL IN THE BLANKS
1, _____ exception is raised when input() hits an EOF without reading any data.
2. exception when a local or global name is not found.
3, exception is raised when an operation is applied to an object of wrong type.
+. When denominator of a division expression is zero, ___ exception is raised.
i While accessing a dictionary, if the given key is not found, exception is raised.
The code which might raise an exception is kept in block.
TRUE/FALSE QUESTIONS
- Exception and error are the same.
1
: 0 ‘ypes of errors can be found during compile time.
a Seed es erty Put producing wrong output is an exception. jon
oes on occurring during runtime which disrupts a program’s exe"
n ie block deals with the exception,
a sey is the correct order of bl
ay be raise
A if it occurs.
locks in exception handling.
id even i : ses?
"if the program is syntactically correct. secchopler 6 : EXCEPTION HANDUNG
ASSERTIONS AND REASONS
DIRECTIONS aa
lowin, juestion, a states ic "
cy fallow gest fe OMEN Of esertion (A) is followed
(a) Both A and R are
() Both A and Ra
(0) Ais true but Ris fase (or p
(@) Ais false (or partly true)
(0 Both A
tue
artly true),
but Ris true,
and R ae false or not fully true,
1. Assertion. Exception handling ig Fesponsible for handling anomalous
execution of a program,
e
4
4
8
3
2
4
z
8
i
a
g
+ Assertion, No matter what exception occurs, you can always make sure that some common action
takes place for all types of exceptions,
Reason, The finally block contains the code that must execute.
NOTE : Answers for OTQs are given at the end of the book.
Ived Problem
1. What is an Exception ?
encountered while executing a program.
2. When is Exception Handling required ?
Solution. The exception handling is ideal for :
* processing exceptional situations
* Processing exceptions for components that cannot handle them directly
* Processing exceptions for widely used components that should not process their own
exceptions
* large projects that require uniform error-processing.
3.
“15 the function of except block in exception handling ? Where does it appear in a program ?
Solution. An except: block isa group of Python statements that are used to handle a
raised exception,
The except: blocks should be placed after each try: block.™
COMPUTER Science wy
nt
cption handling ? cn
Solution, Advantages of exception handling are :
dling separates error-handling code. from normal code,
(Exception hai
(i) 1 clarifies the code and enhances readability.
tes consequences as the error-handling takes place at one place
are
robust, fault-tolerant programs. nd in one,
t ae
What are the advantages of
(iif) Iestimulat
(jo) Tt makes for clear,
When do yon need multiple except handlers ~ exception catcting blocks ?
Solution, Sometimes program has more than one condition to throw exceptions,
gan associate more than one except blocks with a try block. TR Such
What isthe output produced by following code, ifthe input given is: (a) 6 (6)0 (egy
7 lp
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.
(@ There miay or may not have been an exception.
(®) Infinity
‘There may or may not have been an exception.
(0) There may or may not have been an exception.
(@ You should have given either an int or a float
There may or may not have been an exception.
What is the purpose of the finally clause of a try-catch-finally statement ?
Solution. The finally clause is used to provide the capability to execute code no matter whaler
an exception is thrown or caught.
Identify the type of exception for the codes and inputs given below :
(@) input as "kK" () for ainrange(®, 9)*
i print(20/a)
x= int(input("Please enter a number:"))
(c) import mymodule
( mylist = [2,34]
@ x=8
Print (x) print(mylist(4])
() import math @ fillenane = great
a =math.pow(1000@0, 100000) open("graet-txt™» ©
(a) NameError
(¢) ImportError
Solution. (a) ValueError — (b) ZeroDivisionError
(g) 1OError
(©) IndexError —(f) OverflowError4g: EXCEPTION HANDUNG
cchoplet
preict the output ofthe following code for these function calls:
(a) divide(2, 1) (b) divide(2, 0) (0) 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.
(@ divide(2, 1) result is2
executing finally clause
(divide, 0) division by zero!
executing finally clause
(0 divide("2", “1”)
executing finally clause
Traceback (most recent call last):
File "", line 1, in
divide("2", "1")
File "C:/test16.py", line 22, in divide
result = x/y
TypeError: unsupported operand type(s) for /: ‘str’ and'str’
ACERT ES
GUIDEUINE:
NCERT Chapter 1 : Exception Handling in Python
1. “Every syntax error is an exception but every exception cannot be a syntax error.” Justify the statement,
Ans. An exception means occurrence of some unexpected event. Syntax error occurs when some
language rules are violated, which is unexpected event and hence can be termed as exception.
However, exception means occurrence of unexpected event causing program disruption during
runtime, while syntax errors are caught during compile time only.
Hence “every syntax error is an exception but every exception cannot be a syntax error.”
When are the following built-in exceptions raised ? Give examples to support your answers.
SITOINGERT: QUESTIONS:
(9) ImportError (b) JOError ()NameError__(@) ZeroDivisionE ror
41s. For exception details, refer to Table 6.1. For examples of these exceptions :
| \@) Refer to Q. 8(c) (b) Refer to Q. 8(g)
| (0) Refer to Q. 8(d) (d) Refer to Q. 8(b)2
272 COMPUTER Sctencg
van
A. What i the use of a maise statement 2 Write a code 10 accept te muy Moe,
y cxexption shld be raise if the nser enters the second mane 4 :
Ans. The
cept
itself. ePtlone ate ray
ban,
a= int( input ("Enter value for a :"))
nt ( input
1S aM
* a dy
(ie MOMiNaloy) :
priate
raise keyword is used to manually raise an exception lke «
“Enter value for b :"))
if b=:
raise ZeroDivisionError # raising exception using raise key,
print(a/b) ord
except ZeroDivisionError:
print("Please enter non-zero value for b.")
4 Ug sscert statemnt i Question No. 3 lo test the division expression in the program,
int (input ("Enter value for a :"))
b= int(input("Enter value for b :"))
@, “Value for b must be non-zero”
assert
print(a/b)
i cen below and fill in the blanks.
he code
print (“Learning Exceptions...")
try:
numi = int(input (“Enter the first number")
nun2 = int(input ("enter the second number”) )
quotient = (numi/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("Nunber 2 should not be zero”)
else:
print("Great .. you are a good programmer")
EE # to be executed at the end
print ("JOB OVER... GOGET SOME REST")
Ans.
print (“Learning Exceptions...")
AoA
unl = int (input ("Enter the first number"))
nun? = int (input("Enter the second number”) )
quotient = (num /num2)
print("Both the numbers entered were correct")
except ValueError: #1 to enter only integers
print ("Please enter only numbers")
a?chopter 6
EXCEPTION HANDUNG,
except ZeroDivisionrror:
print
else:
"Denominator should not be zero
print("Great .. you are a good Programmer)
finally: # to be executed at the ond
print("JOB OVER. .
You have learnt how to use
arguments for a method (say
+ GOGET Some REST")
a ali in Class XI. Write a cade where you use the wrong number of
SAMO) or pow )). Use the exception handling process to catch the ValueError
exeeption.
Ans.
import math
print ("Code to test wrong TYPE of arguments
try:
num
")
nt (input (“Enter the First nunber"))
result =math.sqrt(numt)
print (“Sqrt:", result1)
except Valuetrror:
# to enter only integers
print (“Please enter only Positive numbers")
try:
num2
result2
nt (input (“Enter the second number")
‘ath. pow(numl, num2)
print ("Pow:", result2)
except Valuefrror:
# to enter only integers
print ("Please enter only numbers")
finally: # to be executed at the end
print ("Tested only wrong types; Wrong no. of requires requires *args")
Code to test wrong TYPE of arguments
Enter the first number-9
Please enter only Positive numbers
Enter the second numberk
Please enter only numbers
Tested only wrong types; Wrong no. of requires requires *args
Code to test wrong TYPE of arguments
Enter the first numberé
Sqrt: 2.449489742783178
Enter the second number4
Pow: 1296.0 i
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. 7,
Ans. Refer to section 6.4.4. /COMPUTER SCIENCE yp
rH
274
hy,
GL OSSA RY
exception ‘An onomolous sivotion encountered by the program.
Sox evar Programing language's grammar rules voaion err.
‘comple time errorEror that the compiler/nterpreter con find during compilotion
un time error Error during program execution
Assignment
1. What is exception ? What is exception handling ?
2. Why is exception handling necessary ?
3. How do you raise an exception? Give code example.
4. How do you handle an exception in Python ?
5. Describe the keyword try. What is the role of try block ?
6. Predict the output by following code :
import math
def F(x):
if x<=@:
raise ValueError(‘#: argument
must be greater than zero’)
return math. sqrt(x)+2
def g(x):
y= F(x)
print (y>2)
try:
(1)
@(-1)
except Exception, e:
print ‘Exception’, e.message
7. Which ofthe following two codes will print “File does not exist” if the file being opened doe nates!
(®) if Filename ! © try:
f = open(filename, 'r’) f= open(filenane, '")
else: except I0Error: -
print ("file does not exist") print ("file does nat exist )
8. Which of the following four outputs is produced by the code that follows ?
output 1:
“2-1 output 2:
zs “2-1 :
© integer division or modulo by zero eae division or modulo PY 2
11
206: EXCEPTION HANDLING.
oper
os
output 3: output 4:
52 “2-1
0,5 -1 “1-1
Poe by zero © Exception occurred
1
1.02
0.5
Given code is :
for x in range(-2, 3
print (x, sep
try:
print (1/x, end =" ")
except ZeroDivisiontrror as e :
print (str(e) )
except :
print ("Exception occurred")
9. Find the errors in following code fragments +
@
"ys
fs = open("/notthere")
exception I0Error:
Print ("The File does not exist, exitin,
1g Bracefully")
print (“This line will always print")
() try:
fh = open(“abc. txt"
try:
hd = open(“new1.txt’
except ValueError:
print (“The file does not exist, exiting gracefully")
(def ret() :
sqr
ise
while True :
return sqrs[i]
its
et () next()
[ x##2 for xin range(4, 10) }
10. Write a function read a Time class objec 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.
ML Write a Program to read details of student for result preparation. Incorporate all possible
®xception-handling codes such as ValueEtror, IndexError, ZeroDivisionError, user-defined exceptions
etc, :