Exception Handling - Sumita Arora-Pages
Exception Handling - Sumita Arora-Pages
Exception Handling
A P P E N D I X
In This Chapter
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
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
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.
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
NOTE
Unhandled exceptions will cause Python to halt execution.
A.16 COMPUTER SCIENCE WITH PYTHON – XII
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
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
result of 10 / 5 = 2
Su
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 :
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.
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.
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 :
a
or
But the above code did not tell which caused the error.
try:
# code
m
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
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
except ValueError:
print ("Could not convert data to an integer.")
except ZeroDivisionError:
print ("Division by zero error")
©
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
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.
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
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.
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
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
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
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
9. Predict the output of the following code for these function calls:
(a) divide(2, 1) (b) divide(2, 0) (c) divide(“2”, “1”)
a
Solution.
or
(a) divide(2, 1) result is 2
executing finally clause
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
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
try:
num2 = int(input("Enter the second number"))
Su
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
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")
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.