0% found this document useful (0 votes)
61 views17 pages

Exception Handling - Sumita Arora-Pages

This document provides an overview of exception handling in Python, detailing the types of errors that can occur during program execution and how to manage them using try and except blocks. It explains the concepts of exceptions, the advantages of using exception handling, and includes examples of built-in exceptions and how to handle multiple exceptions. Additionally, it covers the use of finally blocks to ensure certain code runs regardless of whether an exception occurs.

Uploaded by

thanoshu55
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)
61 views17 pages

Exception Handling - Sumita Arora-Pages

This document provides an overview of exception handling in Python, detailing the types of errors that can occur during program execution and how to manage them using try and except blocks. It explains the concepts of exceptions, the advantages of using exception handling, and includes examples of built-in exceptions and how to handle multiple exceptions. Additionally, it covers the use of finally blocks to ensure certain code runs regardless of whether an exception occurs.

Uploaded by

thanoshu55
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/ 17

APPENDIX E : EXCEPTION HANDLING

Exception Handling
A P P E N D I X

In This Chapter

E.1 Introduction E.3 Concept of


Exception Handling

a
E.2 Exceptions and
Exception Handling E.4 Exception Handling in Python

or
Ar
ita
m

E.1 Introduction
Su

When you create and develop programs, errors occur naturally. Sometimes, you misspell a
name or keyword, or sometimes you unknowingly change the symbols. These are very
common and easy to handle errors. But programming is not that easy and errors are not that
©

simple. So, to handle virtually any type of errors that may occur, language developers have
created numerous ways to catch and prevent them. Python also supports a specific and
well-defined mechanism of catching and preventing errors of any type that may occur. This
mechanism is known as Exception Handling. In this chapter you are going to learn about
exception handling techniques in Python, different types of errors that may occur and ways to
avoid them.

A.13
A.14 COMPUTER SCIENCE WITH PYTHON – XII

E.2 Exceptions and Exception Handling


Exception, in general, refers to some contradictory or unexpected situation or in short, an error
that is unexpected. During program development, there may be some cases where the
programmer does not have the certainty that this code-fragment
is going to work right, either because it accesses to resources that Exception
do not exist or because it gets out of an unexpected range, etc. Contradictory or Unexpected
situation or unexpected error,
These types of anomalous situations are generally called exceptions during program execution, is
and the way to handle them is called exception handling. known as Exception.
Broadly there are two types of errors :
(i) Compile-time errors. These are the errors resulting out of violation of programming
language’s grammar rules e.g., writing syntactically incorrect statement like :
print ("A" + 2)
will result into compile-type error because of invalid syntax. All syntax errors are
reported during compilation.

a
(ii) Run-time errors. The errors that occur during runtime because of unexpected situations.

or
Such errors are handled through exception handling routines of Python. Exception
handling is a transparent and nice way to handle program errors.
Ar
Many reasons support the use of exception handling. In other words, advantages of exception
handling are :
(i) Exception handling separates error-handling code from normal code.
ita

(ii) It clarifies the code (by removing error-handling code from main line of program) and
enhances readability.
m

(iii) It stimulates consequences as the error-handling takes place at one place and in one
manner.
Su

(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 disrupted.
©

Some common examples of Exceptions are :


m Divide by zero errors
m Accessing the elements of an array beyond its range
m Invalid input
m Hard disk crash
m Opening a non-existent file Exception Handling
Way of handling anomalous
m Heap memory exhausted situations in a program-run, is
For instance, consider the following code : known as Exception Handling.
>>> print (3/0)
If you execute above code, you’ll 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
APPENDIX E : EXCEPTION HANDLING A.15

This message is generated by default exception handler of Python. The default exception
handler does the following upon occurrence of an Exception :
(i) Prints out exception description
(ii) Prints the stack trace, i.e., hierarchy of methods where the exception occurred
(iii) Causes the program to terminate.

E.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 program flow should be somewhat
like the one shown in Fig. E.1.
The raising of imaginary
error flag is called throwing 1 3

a
or raising an error. When an Write code
such that it Call
2 the
error is thrown, the overall

or
raises an
error-flag every If error flag Error-
system responds by catching time something handling
is raised then routine
the error. And surrounding a goes wrong
Ar
block of error-sensitive- throw exception catch exception
code-with-exception-handling
is called trying to execute a
ita
Figure E.1 Concept of exception handling.
block.
Some terminology used within exception handling follows.
m

Description Python Terminology


Su

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 except/exception
(i.e., problem). block or catch block
The sequence of method calls that brought control to the Stack trace
point where the exception occurred.

When to Use Exception Handling


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

NOTE
Unhandled exceptions will cause Python to halt execution.
A.16 COMPUTER SCIENCE WITH PYTHON – XII

E.4 Exception Handling in Python


Exception Handling in Python involves the use of try and except clauses in the following format
wherein the code that may generate an exception is written in the try block and the code for
handling exception when the exception is raised, is written in except block.

See below :

try :
#write here the code that may generate an exception
except :
#write code here about what to do when the exception has occurred

For instance, consider the following code :

try :

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

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

The output produced by above code is as shown below :

result of 10 / 5 = 2
Su

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 ; it
is now showing what you defined under the exception block.
Consider another code that handles an exception raised when a code tries conversion from text
to a number :
try:
x = int("XII")
except:
print ("Error converting'XII'to a number")

The output generated from above code is not the usual error now, it is :

Error converting ‘XII’ to a number

Consider program E.1 that is expanded version of the above example. It error- checks a user’s
input to make sure an integer is entered.
APPENDIX E : EXCEPTION HANDLING A.17

E.1 Write a program to ensure that an integer is entered as input and in case any other value is entered, it
displays a message – ‘Not a valid integer’
rogram ok = False
while not ok :
try :
numberString = input("Enter an integer:")
n = int(numberString)
ok = True
except :
print ("Error! Not a valid integer.")
Enter an integer: oo7
Error! Not a valid integer.
Enter an integer: 007

a
E.4.1 General Built-in Python Exceptions

or
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
Ar
exceptions in Python are being listed below in Table E.1.

Table E.1 Some built-in Exceptions


ita
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
m

empty string when they hit EOF.)


IO Error Raised when an I/O operation (such as a print statement, the built-in open( ) function
Su

or a method of a file object) fails for an I/O-related reason, e.g., “file not found” or “disk
full”.
NameError Raised when a local or global name is not found. This applies only to unqualified names.
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.)
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.
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 IndexError.
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.
KeyboardInterrupt Raised when keys Esc, Del or Ctrl+C is pressed during program execution and normal
program flow gets disturbed.
A.18 COMPUTER SCIENCE WITH PYTHON – XII

Following program E.2 handles an error that may occur while opening a file.

E.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 Error opening file
myfile.txt exists and contains some data otherwise it shows an
output as :

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


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

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

E.4.2 Second Argument of the except Block Ar


You can also provide a second argument for the except block, which gives a reference to the
exception object. You can do it in following format :
ita

try:
# code
m

except <ExceptionName> as <exArgument> :


# handle error here
Su

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
here – gets reference of raised exception
except ZeroDivisionError as e :
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


The message associated with the exception
Exception – division by zero

E.4.3 Handling Multiple Errors


Multiple types of errors may be captured and processed differently. It can be useful to provide 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.
APPENDIX E : EXCEPTION HANDLING A.19

This is done as per following format :

try:
#:
except <exceptionName1> :
#:
except <exceptionName2> :
#:
The except block without any exception
except : name will handle the rest of the exceptions
#:
else :
#If 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 E.3 illustrates the same.

a
E.3

or
Program to handle multiple exceptions.
try:
rogram
my_file = open("myfile.txt")
my_line = my_file.readline()
Ar
my_int = int(s.strip())
ita

my_calculated_value = 101 / my_int


These three except blocks will catch and
except IOError: handle IOError , ValueError and
m

print ("I/O error occurred") ZeroDivisionError exceptions respectively


Su

except ValueError:
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 of the exceptions
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/O error occurred

Exception Handling – execution order


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

E.4.4 The finally Block


You can also use a finally: block along with a try: block, just like you use except: block, e.g., as :
try:
# statements that may raise exception
[except:
# handle exception here]
finally:
# statements that will always run
The difference between an except: block and the finally: block is that the finally: block is a place
that contains any code that must execute, whether the try: block raised an exception or not.
For example,
try:
fh = open("poems.txt", "r+")
This statement will always be

a
fh.write("Adding new line") executed in the end
finally:

or
print ("Error: can\'t find file or read data")
Ar
You may combine finally: with except: clause. In such a combination, the except: block will get
executed only in case an exception is raised and finally: block will get executed ALWAYS, in
the end. Following code illustrates it :
ita
try:
fh = open("poem1.txt", "r")
print (fh.read())
m

except:
Su

print ("Exception Occurred")


finally:
print ("Finally saying goodbye.")
©

The output produced by above code will be :


This is printed because except: block
Exception Occurred got executed when exception occurred.
This is printed because
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.

E.4.5 Raising/Forcing an Exception


In Python, you can use the raise keyword to raise/force an exception. That means, you as
programmer can force an exception to occur through raise keyword. It can also pass a custom
message to your exception handling module. For example :
raise <exception> (<message>)
The exception raised in this way should be a pre-defined Built-in exception. Consider following
code snippet that forces a ZeroDivisionError exception to occur without actually dividing a
value by zero :
APPENDIX E : EXCEPTION HANDLING A.21
try : Notice this raise statement is
a = int(input("Enter numerator :")) raising built-in exception
ZeroDivisionError with a custom
b = int(input("Enter denominator :")) message, that follows the
exception name
if b == 0 :
raise ZeroDivisionError(str(a) + "/0 not possible")
print (a/b)
except ZeroDivisionError as e :
print ("Exception", str(e))

The output produced by above code is :


Enter numerator : 7
Enter denominator : 0 This was the custom-message sent; printed
as str(e) because the exception
Exception 7/0 not possible reference was received in e

a
Python assert Statement

or
In some situations, you have a clear idea about the requirements and test-conditions required. So in programs
Ar
where you know the likely results of some conditions and where results being different from the expected results
can crash the programs, you can use Python assert statement if the condition is resulting as expected or not.
Python’s assert statement is a debugging aid that tests a condition. If the condition is true, it does nothing and
ita
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 ]
m

Specify the optional, custom message


For example, consider the following code : through error_message
Su

print("Enter the Numerator: ")


Custom Error message
n = int(input())
print("Enter the Denominator: ")
specified
NOTE
This error message will be The assert keyword in Python
d = int(input())
©

printed only when the given is used when we need to


assert d != 0, "Denominator must not be 0" condition d != 0 results detect problems early.
into false.
print("n/d =", int(n/d))

Benefits of Exception Handling


nt Exception provides the means to separate the details of what
k Poi
hec to do when something out of the ordinary happens from the
C E.1
main logic of a program. In short, the advantages of exception
1. Name the block that encloses the code handling are :
that may encounter anomalous situations.
2. In which block can you raise the
(i) Exception handling separates error-handling code from
exception ? normal code.
3. Which block traps and handles an (ii) It clarifies the code and enhances readability.
exception ? (iii) It stimulates consequences as the error-handling takes
4. Can one except block sufficiently trap place at one place and in one manner.
and handle multiple exceptions ?
(iv) It makes for clear, robust,
5. Which block is always executed no
matter which exception is raised ?
fault-tolerant programs. O T E N
All exceptions are sub-classes
6. Name the root class for all exceptions. of Exception class.
A.22 COMPUTER SCIENCE WITH PYTHON – XII

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

Objective Type Questions OTQs


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

a
(c) Runtime error (d) Exception

or
2. An unexpected event that occurs during runtime and causes program disruption, is called ______ .
(a) Compile time error (b) Logical error
(c) Runtime error Ar
(d) Exception
3. Which of the following keywords are not specific to exception handling ?
(a) try (b) except (c) finally (d) else
ita

4. Which of the following blocks is a ‘must-execute’ block ?


(a) try (b) except (c) finally (d) else
m

5. Which keyword is used to force an exception ?


(a) try (b) except (c) raise (d) finally
Su

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.
4. When denominator of a division expression is zero, ______ exception is raised.
5. While accessing a dictionary, if the given key is not found, ______ exception is raised.
6. The code which might raise an exception is kept in ______ block.

True/False Questions
1. Exception and error are the same.
2. All types of errors can be found during compile time.
3. A program running properly put producing wrong output is an exception.
4. Unexpected rare condition occurring during runtime which disrupts a program’s execution is an
exception.
5. The except block deals with the exception, if it occurs.
6. try, except, finally is the correct order of blocks in exception handling.
APPENDIX E : EXCEPTION HANDLING A.23

Assertions and Reasons


DIRECTIONS
In the following question, a statement of assertion (A) is followed by a statement of reason ( R).
Mark the correct choice as :
(a) Both A and R are true and R is the correct explanation of A.
(b) Both A and R are true but R is not the correct explanation of A.
(c) A is true but R is false (or partly true).
(d) A is false (or partly true) but R is true. (e) Both A and R are false or not fully true.
1. Assertion. Exception handling is responsible for handling anomalous situations during the
execution of a program.
Reason. Exception handling handles all types of errors and exceptions.
2. Assertion. Exception handling code is separate from normal code.
Reason. Program logic is different while exception handling code uses specific keywords to handle

a
exceptions.

or
3. Assertion. Exception handling code is clear and block based in Python.
Reason. The code where unexpected runtime exception may occur is separate from the code where
Ar
the action takes place when an exception occurs.
4. Assertion. No matter what exception occurs, you can always make sure that some common action
takes place for all types of exceptions.
ita

Reason. The finally block contains the code that must execute.

Answers
m

MCQs
Su

1. (a) 2. (d) 3. (d) 4. (c) 5. (c)

Fill in the blanks


1. EOFError 2. NameError 3. TypeError 4. ZeroDivisionError 5. KeyError 6. try
©

True/False
1. False 2. False 3. False 4. True 5. True 6. True

Assertions/Reasons
1. (c) 2. (a) 3. (a) 4. (a)

Solved Problem
1. What is an Exception ?
Solution. Exception in general refers to some contradictory or unusual situation which can be
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.
A.24 COMPUTER SCIENCE WITH PYTHON – XII

3. What is the function of except block in exception handling ? Where does it appear in a program ?
Solution. An except: block is a group of Python statements that are used to handle a raised exception.
The except: blocks should be placed after each try: block.
4. What are the advantages of exception handling ?
Solution. Advantages of exception handling are :
(i) Exception handling separates error-handling code from normal code.
(ii) It clarifies the code 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.
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, one
can associate more than one except blocks with a try block.
6. What is the output produced by following code, if the input given is : (a) 6 (b) 0 (c) 6.7 (d) “a”

a
try:

or
x = float(input("Your number:"))
inverse = 1.0/x
except ValueError:
Ar
print ("You should have given either an int or a float")
except ZeroDivisionError:
ita

print ("Infinity")
finally:
m

print ("There may or may not have been an exception.")


Solution.
Su

(a) There may or may not have been an exception.


(b) Infinity
There may or may not have been an exception.
©

(c) There may or may not have been an exception.


(d) You should 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 ?
Solution. The finally clause is used to provide the capability to execute code no matter whether or not
an exception is thrown or caught.
8. Identify the type of exception for the codes and inputs given below :
(a) #input as "K" (b) for a in range(0, 9):
x = int(input("Please enter a number:")) print(20/a)

(c) import mymodule

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


print(X) print(mylist[4])
(f) import math (g) filename = "great.txt"
a = math.pow(100000, 100000) open("graet.txt", "r")
APPENDIX E : EXCEPTION HANDLING A.25

Solution. (a) ValueError (b) ZeroDivisionError (c) ImportError (d) NameError


(e) IndexError (f) OverflowError (g) IOError

9. Predict the 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")

a
Solution.

or
(a) divide(2, 1) result is 2
executing finally clause

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


Ar
executing finally clause
ita

(c) divide(“2”, “1”)


executing finally clause
m

Traceback (most recent call last):


Su

File "<pyshell#46>", line 1, in <module>


divide("2", "1")
File "C:/test16.py", line 22, in divide
result = x/y
©

TypeError: unsupported operand type(s) for /:'str'and'str'

Guidelines to NCERT Questions NCERT


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.”
2. When are the following built-in exceptions raised ? Give examples to support your answers.
(a) ImportError (b) IOError (c) NameError (d) ZeroDivisionError
Ans. For exception details, refer to table 1. For examples of these 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)
A.26 COMPUTER SCIENCE WITH PYTHON – XII

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).
Ans. The raise keyword is used to manually raise an exception like exceptions are raised by Python
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 program.
Ans. a = int(input("Enter value for a :"))

a
b = int(input("Enter value for b :"))

or
assert b != 0, "Value for b must be non-zero"
print(a/b) Ar
5. Define the following : a) Exception Handling (b) Throwing an exception (c) Catching an exception
Ans. (a) Refer Section E.3 ; (b) Refer Section E.5 ; (c) Refer Section E.4
ita
6. Explain catching exceptions using try and except block.
Ans. (a) Refer Section E.4
m

7. Consider the code given below and fill in the blanks.

print ("Learning Exceptions...")


Su

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")
Ans.
print ("Learning Exceptions...")
try:
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
APPENDIX E : EXCEPTION HANDLING A.27
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.
Ans.

a
import math

or
print ("Code to test wrong TYPE of arguments")
try:
Ar
num1 = int(input ("Enter the first number"))
result1 = math.sqrt(num1)
print ("Sqrt:", result1)
ita

except ValueError: # to enter only integers


print ("Please enter only Positive numbers")
m

try:
num2 = int(input("Enter the second number"))
Su

result2 = math.pow(num1, num2)


print ("Pow:", result2)
except ValueError: # 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 number6
Sqrt: 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. 7.
Ans. Refer to section E4.4.
A.28 COMPUTER SCIENCE WITH PYTHON – XII

Glossary
Exception An anomalous situation encountered by the program.
Syntax error Programming language’s grammar rules violation error.
Compile time errorError that the compiler/interpreter can find during compilation.
Run 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 ?

a
5. Describe the keyword try. What is the role of try block ?
6. Predict the output by following code :

or
import math
def f(x): Ar
if x <= 0 :
raise ValueError('f: argument
must be greater than zero')
ita

return math.sqrt(x)+2

def g(x):
m

y = f(x)
Su

print (y > 2)

try:
g(1)
©

g(-1)
except Exception, e:
print'Exception', e.message
7. Which of the following two codes will print “File does not exist” if the file being opened does not exist ?
(a) if filename != " ": (b) try:
f = open(filename,'r') f = open(filename,'r')
else: except IOError:
print ("file does not exist") print ("file does not exist")

8. Which of the following four outputs is produced by the code that follows ?

output 1 : output 2 :
-2 -1 -2 -1
-1 -1 -1 -1
0 integer division or modulo by zero 0 integer division or modulo by zero
1 1
2 0
APPENDIX E : EXCEPTION HANDLING A.29
output 3 : output 4 :
-2 -2 -1
-0.5 -1 -1 -1
–1.0 0 0 Exception occurred
division by zero
1
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 :

a
print (str(e) )
except :

or
print ("Exception occurred")
9. Find the errors in following code fragments : Ar
(a) try:
fs = open("/notthere")
ita
exception IOError:
print ("The file does not exist, exiting gracefully")
print ("This line will always print")
m

(b) try:
Su

fh = open("abc.txt")
try :
fh1 = open("new1.txt", "r")
©

except ValueError:
print ("The file does not exist, exiting gracefully")

(c) def ret() :


sqrs = [ x**2 for x in range(1, 10) ]
i=0
while 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. Incorporate all possible
exception-handling codes such as ValueError, IndexError, ZeroDivisionError, user-defined exceptions
etc.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy