0% found this document useful (0 votes)
2 views

Unit VI File Handling and Exception Handling

The document provides an overview of file I/O handling and exception handling in Python, including how to read from and write to files, as well as handling exceptions. It explains the use of the print() function, keyboard input, and various file access modes. Additionally, it discusses file object attributes, reading lines, and using the 'with' statement for file operations to ensure proper resource management.

Uploaded by

panditsahil696
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit VI File Handling and Exception Handling

The document provides an overview of file I/O handling and exception handling in Python, including how to read from and write to files, as well as handling exceptions. It explains the use of the print() function, keyboard input, and various file access modes. Additionally, it discusses file object attributes, reading lines, and using the 'with' statement for file operations to ensure proper resource management.

Uploaded by

panditsahil696
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Padmashri Dr.

Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar


PWP-22616,CM

h
Unit VI

ik
File I/O Handling and Exception Handling
ha
.S
6a Write Python code for the given reading values from keyboard
6b Read data from the given file.
.A

6c Write the given data to a file.


.A

6d Handle the given exceptions through Python program.


of
Pr

1
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

Printing to the Screen


 The print() function prints the given object to the standard output device (screen) or to the
text stream file.
 The full syntax of print() is:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
print() Parameters
 objects - object to the printed. * indicates that there may be more than one object
 sep - objects are separated by sep. Default value: ' '
 end - end is printed at last
 file - must be an object with write(string) method. If omitted it, sys.stdout will be used
which prints objects on the screen.
 flush - If True, the stream is forcibly flushed. Default value: False
 Example 1: How print() works in Python?

h
print("Python is fun.")

ik
a=5
# Two objects are passed
print("a =", a)
b=a ha
.S
# Three objects are passed
print('a =', a, '= b')
.A

 Output
Python is fun.
a=5
.A

a=5=b
 In the above program, only objects parameter is passed to print() function (in all three
of

print statements).
 Hence,
Pr

i. ' ' separator is used. Notice, the space between two objects in output.
ii. end parameter '\n' (newline character) is used. Notice, each print statement
displays the output in the new line.
iii. file is sys.stdout. The output is printed on the screen.
iv. flush is False. The stream is not forcibly flushed.
 Example 2: print() with separator and end parameters
a=5
print("a =", a, sep='00000', end='\n\n\n')
print("a =", a, sep='0', end='')
 Output
a =000005
a =05

2
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

 Example 3: print() with file parameter


sourceFile = open('sample1.txt', 'w')
print('Pretty cool, huh!', file = sourceFile)
sourceFile.close()
 This program tries to open the sample1.txt in writing mode. If this file doesn't
exist, sample1.txt file is created and opened in writing mode.
 Here, we have passed sourceFile file object to the file parameter. The string object 'Pretty
cool, huh!' is printed to sample1.txt file (check it in your system).
 Finally, the file is closed using close() method.

Reading Keyboard Input


 Python provides built-in function to read a line of text from standard input, which by
default comes from the keyboard.

h
 The input([prompt]) function assumes the input is a valid Python expression and returns

ik
the evaluated result to you.
str = input("Enter your input: ")

ha
print ("Received input is : ", str)
 This would produce the following result against the entered input −
.S
Enter your input: Hi
Recieved input is : Hi
.A

Python File I/O


 File is a named location on disk to store related information. It is used to permanently
.A

store data in a non-volatile memory (e.g. hard disk).


 Since, random access memory (RAM) is volatile which loses its data when computer is
of

turned off, we use files for future use of the data.


 When we want to read from or write to a file we need to open it first. When we are done,
Pr

it needs to be closed, so that resources that are tied with the file are freed.
 Hence, in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file
1. Opening a File
o Before you can read or write a file, you have to open it using Python's built-in
open() function.
o This function creates a file object, which would be utilized to call other support
methods associated with it.
o Syntax
file object = open(file_name [, access_mode][, buffering])

3
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

o Here are parameter details −


 file_name − The file_name argument is a string value that contains the name
of the file that you want to access.
 access_mode − The access_mode determines the mode in which the file has to
be opened, i.e., read, write, append, etc. A complete list of
possible values is given below in the table. This is optional
parameter and the default file access mode is read (r).
 buffering − If the buffering value is set to 0, no buffering takes place. If the
buffering value is 1, line buffering is performed while accessing a
file. If you specify the buffering value as an integer greater than 1,
then buffering action is performed with the indicated buffer size.
If negative, the buffer size is the system default(default behavior).
o Here is a list of the different modes of opening a file −

h
Sr.No. Modes Description

ik
1 r Opens a file for reading only. The file pointer is placed at

ha
the beginning of the file. This is the default mode.
2 rb Opens a file for reading only in binary format. The file
pointer is placed at the beginning of the file. This is the
.S
default mode.
3 r+ Opens a file for both reading and writing. The file pointer
placed at the beginning of the file.
.A

4 rb+ Opens a file for both reading and writing in binary format.
The file pointer placed at the beginning of the file.
.A

5 w Opens a file for writing only. Overwrites the file if the file
exists. If the file does not exist, creates a new file for
writing.
of

6 wb Opens a file for writing only in binary format. Overwrites


the file if the file exists. If the file does not exist, creates a
Pr

new file for writing.


7 w+ Opens a file for both writing and reading. Overwrites the
existing file if the file exists. If the file does not exist,
creates a new file for reading and writing.
8 wb+ Opens a file for both writing and reading in binary format.
Overwrites the existing file if the file exists. If the file does
not exist, creates a new file for reading and writing.
9 a Opens a file for appending. The file pointer is at the end of
the file if the file exists. That is, the file is in the append
mode. If the file does not exist, it creates a new file for
writing.
10 ab Opens a file for appending in binary format. The file pointer
is at the end of the file if the file exists. That is, the file is in
the append mode. If the file does not exist, it creates a new
file for writing.

4
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology & Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

11 a+ Opens a file for both appending and reading. The file


pointer is at the end of the file if the file exists. The file
opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
12 ab+ Opens a file for both appending and reading in binary
format. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does
not exist, it creates a new file for reading and writing.

The file Object Attributes


 Once a file is opened and you have one file object, you can get various information
related to that file.
 Here is a list of all attributes related to file object −

h
Sr.No. Attribute Description
1 file.closed Returns true if file is closed, false otherwise.

ik
2 file.mode Returns access mode with which file was opened.

ha
3 file.name Returns name of the file.
4 file.softspace Returns false if space explicitly required with
print, true otherwise.
.S
 Example
.A

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
.A

print "Closed or not : ", fo.closed


print "Opening mode : ", fo.mode
of

print "Softspace flag : ", fo.softspace


 This produces the following result −
Pr

Name of the file: foo.txt


Closed or not : False
Opening mode : wb
Softspace flag : 0

2. Reading the file


 To read a file using the python script, the python provides us the read() method. The
read() method reads a string from the file. It can read the data in the text as well as binary
format.
 The syntax of the read() method is given below.
fileobj.read(<count>)

5
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology &amp; Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

 Here, the count is the number of bytes to be read from the file starting from the beginning
of the file. If the count is not specified, then it may read the content of the file until the
end.
 Consider the following example.
 Example
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt","r");
#stores all the data of the file into the variable content
content = fileptr.read(9);
# prints the type of the data stored in the file
print(type(content))
#prints the content of the file
print(content)

h
#closes the opened file
fileptr.close()

ik
 Output:

ha
<class 'str'>
Hi, I am
.S
Read Lines of the file
 Python facilitates us to read the file line by line by using a function readline().
.A

 The readline() method reads the lines of the file from the beginning, i.e., if we use the
readline() method two times, then we can get the first two lines of the file.
.A

 Consider the following example which contains a function readline() that reads the first
line of our file "file.txt" containing three lines.
 Example
of

#open the file.txt in read mode. causes error if no such file exists.
Pr

fileptr = open("file.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readline();
# prints the type of the data stored in the file
print(type(content))
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()
 Output:
<class 'str'>
Hi, I am the file and being used as

6
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology &amp; Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

Looping through the file


 By looping through the lines of the file, we can read the whole file.
 Example
#open the file.txt in read mode. causes an error if no such file exists.
fileptr = open("file.txt","r");
#running a for loop
for i in fileptr:
print(i) # i contains each line of the file
 Output:
Hi, I am the file and being used as
an example to read a
file in python.

h
Writing the file
 To write some text to a file, we need to open the file using the open method with one of

ik
the following access modes.

ha
a: It will append the existing file. The file pointer is at the end of the file. It
creates a new file if no file exists.
.S
w: It will overwrite the file if any file exists. The file pointer is at the beginning of
the file.
 Consider the following example.
.A

#open the file.txt in append mode. Creates a new file if no such file exists.
fileptr = open("file.txt","a");
.A

#appending the content to the file


fileptr.write("Python is the modern day language. It makes things so simple.")
of

#closing the opened file


fileptr.close();
Pr

 Now, we can see that the content of the file is modified.


File.txt:
Hi, I am the file and being used as
an example to read a
file in python.
Python is the modern day language. It makes things so simple.
 Consider another example
#open the file.txt in write mode.
fileptr = open("file.txt","w");
#overwriting the content of the file
fileptr.write("Python is the modern day language. It makes things so simple.")

7
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology &amp; Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

#closing the opened file


fileptr.close();
 Now, we can check that all the previously written content of the file is overwritten with
the new text we have passed.
File.txt:
Python is the modern day language. It makes things so simple.

Using with statement with files


 The with statement was introduced in python 2.5.
 The with statement is useful in the case of manipulating the files.
 The with statement is used in the scenario where a pair of statements is to be executed
with a block of code in between.
 The syntax to open a file using with statement is given below.

h
with open(<file name>, <access mode>) as <file-pointer>:

ik
#statement suite
 The advantage of using with statement is that it provides the guarantee to close the file

ha
regardless of how the nested block exits.
 It is always suggestible to use the with statement in the case of file s because, if the break,
.S
return, or exception occurs in the nested block of code then it automatically closes the
file. It doesn't let the file to be corrupted.
 Consider the following example.
.A

with open("file.txt",'r') as f:
content = f.read();
.A

print(content)
 Output:
of

Python is the modern day language. It makes things so simple.


Pr

File Pointer positions


 Python provides the tell() method which is used to print the byte number at which the file
pointer exists.
 Consider the following example.
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
#reading the content of the file
content = fileptr.read();
#after the read operation file pointer modifies. tell() returns the location of the
fileptr.
print("After reading, the filepointer is at:",fileptr.tell())

8
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology &amp; Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

 Output:
The filepointer is at byte : 0
After reading, the filepointer is at 26

Modifying file pointer position


 In the real world applications, sometimes we need to change the file pointer location
externally since we may need to read or write the content at various locations.
 For this purpose, the python provides us the seek() method which enables us to modify
the file pointer position externally.
 The syntax to use the seek() method is given below.
<file-ptr>.seek(offset[, from)
 The seek() method accepts two parameters:
1. offset: It refers to the new position of the file pointer within the file.

h
2. from: It indicates the reference position from where the bytes are to be moved. If it is

ik
set to 0, the beginning of the file is used as the reference position. If it is set to 1, the
current position of the file pointer is used as the reference position. If it is set to 2, the

ha
end of the file pointer is used as the reference position.
 Consider the following example.
.S
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")
#initially the filepointer is at 0
.A

print("The filepointer is at byte :",fileptr.tell())


#changing the file pointer location to 10.
.A

fileptr.seek(10);
#tell() returns the location of the fileptr.
of

print("After reading, the filepointer is at:",fileptr.tell())


 Output:
Pr

The filepointer is at byte : 0


After reading, the filepointer is at 10

3. Close a file Using Python


 When we are done with operations to the file, we need to properly close the file.
 Closing a file will free up the resources that were tied with the file and is done using
Python close() method.
 Python has a garbage collector to clean up unreferenced objects but, we must not rely on
it to close the file.
f = open("test.txt",’r’)
# perform file operations
f.close()

9
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology &amp; Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

 This method is not entirely safe. If an exception occurs when we are performing some
operation with the file, the code exits without closing the file.
 A safer way is to use a try...finally block.
try:
f = open("test.txt", 'r')
# perform file operations
finally:
f.close()

Python Directory
 If there are a large number of files to handle in your Python program, you can arrange
your code within different directories to make things more manageable.
 A directory or folder is a collection of files and sub directories. Python has the os module,

h
which provides us with many useful methods to work with directories (and files as well).

ik
Get Current Directory
 We can get the present working directory using the getcwd() method.

ha
 This method returns the current working directory in the form of a string. We can also
use the getcwdb() method to get it as bytes object.
.S
 Example
import os
.A

print(os.getcwd())
 Output
D:\WPy32-3741\settings
.A

Changing Directory
 We can change the current working directory using the chdir() method.
of

 The new path that we want to change to must be supplied as a string to this method. We
can use both forward slash (/) or the backward slash (\) to separate path elements.
Pr

 It is safer to use escape sequence when using the backward slash.


 Example
import os
os.chdir("D:\\WPy32-3741")
print(os.getcwd())
 Output
D:\WPy32-3741

10
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology &amp; Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

List Directories and Files


 All files and sub directories inside a directory can be known using the listdir() method.
 This method takes in a path and returns a list of sub directories and files in that path. If no
path is specified, it returns from the current working directory.
 Example
import os
os.chdir("D:\\WPy32-3741")
print(os.listdir())
 Output
['ash', 'calcu', 'calculation.py', 'Cars', 'df.py', 'foo', 'IDLE (Python GUI).exe',
'IDLEX.exe', 'info', 'IPython Qt Console.exe', 'Jupyter Lab.exe', 'Jupyter
Notebook.exe', 'license.txt', 'new.py', 'notebooks', 'python-3.7.4', 'Pyzo.exe', 'Qt
Designer.exe', 'Qt Linguist.exe', 'sam1.py', 'Sample', 'scripts', 'settings', 'Spyder

h
reset.exe', 'Spyder.exe', 't', 'temp1.py', 'VS Code.exe', 'we.py', 'WinPython
Command Prompt.exe', 'WinPython Control Panel.exe', 'WinPython

ik
Interpreter.exe', 'WinPython Powershell Prompt.exe']

ha
Making a New Directory
 We can make a new directory using the mkdir() method.
.S
 This method takes in the path of the new directory. If the full path is not specified, the
new directory is created in the current working directory.
 Example
.A

import os
os.mkdir('test')
.A

print(os.listdir())
 Output
of

['.config', '.idlerc', '.ipython', '.jupyter', '.matplotlib', '.ptpython', '.pyzo', '.spyder-


py3', 'as.py', 'as12.py', 'ash.txt', 'cal.py', 'calculation.py', 'callmod.py', 'classattr.py',
Pr

'classattri.py', 'classfun.py', 'classinh.py', 'classsample.py', 'constpara.py',


'countobj.py', 'datahide.py', 'deci.py', 'ds.py', 'erew.py', 'f1.py', 'f3.py', 'file.py',
'file1.py', 'file2.py', 'filebuilt.py', 'fileread.py', 'fr.py', 'fun1.py', 'fwrite.py', 'hj.py',
'ma.py', 'meh.py', 'mehtodoverride.py', 'mehtodoverride1.py', 'methodoverload.py',
'mod1.py', 'multilevel.py', 'nam.py', 'nonpara.py', 'print.py', 'pydistutils.cfg',
'raw.py', 'runtime', 'sam.py', 'sam1.py', 'sample.py', 'sample.txt', 'sample1.txt',
'sd.py', 'sdf.py', 'seaborn-data', 'simple_package', 'test', 'test.py', 'winpython.ini',
'xc.py', '__pycache__']

11
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology &amp; Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

Renaming a Directory or a File


 The rename() method can rename a directory or a file.
 The first argument is the old name and the new name must be supplies as the second
argument.
 Example
import os
os.rename('test','new_one')
print(os.listdir())
 Output
['.config', '.idlerc', '.ipython', '.jupyter', '.matplotlib', '.ptpython', '.pyzo', '.spyder-
py3', 'as.py', 'as12.py', 'ash.txt', 'cal.py', 'calculation.py', 'callmod.py', 'classattr.py',
'classattri.py', 'classfun.py', 'classinh.py', 'classsample.py', 'constpara.py',
'countobj.py', 'datahide.py', 'deci.py', 'ds.py', 'erew.py', 'f1.py', 'f3.py', 'file.py',

h
'file1.py', 'file2.py', 'filebuilt.py', 'fileread.py', 'fr.py', 'fun1.py', 'fwrite.py', 'hj.py',
'ma.py', 'meh.py', 'mehtodoverride.py', 'mehtodoverride1.py', 'methodoverload.py',

ik
'mod1.py', 'multilevel.py', 'nam.py', 'new_one', 'nonpara.py', 'print.py',

ha
'pydistutils.cfg', 'raw.py', 'runtime', 'sam.py', 'sam1.py', 'sample.py', 'sample.txt',
'sample1.txt', 'sd.py', 'sdf.py', 'seaborn-data', 'simple_package', 'test.py',
.S
'winpython.ini', 'xc.py', '__pycache__']

Removing Directory or File


.A

 A file can be removed (deleted) using the remove() method.


 Similarly, the rmdir() method removes an empty directory.
.A

 Example
import os
of

print("Before File Removeing and Before Directory Removeing")


print(os.listdir())
Pr

os.remove('sd.py')
print("After File Removeing")
print(os.listdir())
print("After Directory Removeing")
os.rmdir('new_one')
print(os.listdir())
 Output
Before File Removeing Before Directory Removeing
['.config', '.idlerc', '.ipython', '.jupyter', '.matplotlib', '.ptpython', '.pyzo', '.spyder-
py3', 'as.py', 'as12.py', 'ash.txt', 'cal.py', 'calculation.py', 'callmod.py', 'classattr.py',
'classattri.py', 'classfun.py', 'classinh.py', 'classsample.py', 'constpara.py',
'countobj.py', 'datahide.py', 'deci.py', 'ds.py', 'erew.py', 'f1.py', 'f3.py', 'file.py',
'file1.py', 'file2.py', 'filebuilt.py', 'fileread.py', 'fr.py', 'fun1.py', 'fwrite.py', 'hj.py',

12
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology &amp; Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

'ma.py', 'meh.py', 'mehtodoverride.py', 'mehtodoverride1.py', 'methodoverload.py',


'mod1.py', 'multilevel.py', 'nam.py', 'new_one', 'nonpara.py', 'print.py',
'pydistutils.cfg', 'raw.py', 'runtime', 'sam.py', 'sam1.py', 'sample.py', 'sample.txt',
'sample1.txt', 'sd.py', 'sdf.py', 'seaborn-data', 'simple_package', 'winpython.ini',
'xc.py', '__pycache__']
After File Removeing
['.config', '.idlerc', '.ipython', '.jupyter', '.matplotlib', '.ptpython', '.pyzo', '.spyder-
py3', 'as.py', 'as12.py', 'ash.txt', 'cal.py', 'calculation.py', 'callmod.py', 'classattr.py',
'classattri.py', 'classfun.py', 'classinh.py', 'classsample.py', 'constpara.py',
'countobj.py', 'datahide.py', 'deci.py', 'ds.py', 'erew.py', 'f1.py', 'f3.py', 'file.py',
'file1.py', 'file2.py', 'filebuilt.py', 'fileread.py', 'fr.py', 'fun1.py', 'fwrite.py', 'hj.py',
'ma.py', 'meh.py', 'mehtodoverride.py', 'mehtodoverride1.py', 'methodoverload.py',
'mod1.py', 'multilevel.py', 'nam.py', 'new_one', 'nonpara.py', 'print.py',
'pydistutils.cfg', 'raw.py', 'runtime', 'sam.py', 'sam1.py', 'sample.py', 'sample.txt',

h
'sample1.txt', 'sdf.py', 'seaborn-data', 'simple_package', 'winpython.ini', 'xc.py',

ik
'__pycache__']

ha
After Directory Removeing
['.config', '.idlerc', '.ipython', '.jupyter', '.matplotlib', '.ptpython', '.pyzo', '.spyder-
.S
py3', 'as.py', 'as12.py', 'ash.txt', 'cal.py', 'calculation.py', 'callmod.py', 'classattr.py',
'classattri.py', 'classfun.py', 'classinh.py', 'classsample.py', 'constpara.py',
'countobj.py', 'datahide.py', 'deci.py', 'ds.py', 'erew.py', 'f1.py', 'f3.py', 'file.py',
.A

'file1.py', 'file2.py', 'filebuilt.py', 'fileread.py', 'fr.py', 'fun1.py', 'fwrite.py', 'hj.py',


'ma.py', 'meh.py', 'mehtodoverride.py', 'mehtodoverride1.py', 'methodoverload.py',
.A

'mod1.py', 'multilevel.py', 'nam.py', 'nonpara.py', 'print.py', 'pydistutils.cfg',


'raw.py', 'runtime', 'sam.py', 'sam1.py', 'sample.py', 'sample.txt', 'sample1.txt',
'sdf.py', 'seaborn-data', 'simple_package', 'winpython.ini', 'xc.py', '__pycache__']
of

 However, note that rmdir() method can only remove empty directories.

Pr

In order to remove a non-empty directory we can use the rmtree() method inside
the shutil module.
 Example
import shutil
shutil.rmtree('simple_package')

13
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology &amp; Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

Python Exceptions
 An exception can be defined as an abnormal condition in a program resulting in the
disruption in the flow of the program.
 Whenever an exception occurs, the program halts the execution, and thus the further code
is not executed. Therefore, an exception is the error which python script is unable to
tackle with.
 Python provides us with the way to handle the Exception so that the other part of the code
can be executed without any disruption. However, if we do not handle the exception, the
interpreter doesn't execute all the code that exists after the that.
Common Exceptions
 A list of common exceptions that can be thrown from a normal python program is given
below.
1. ZeroDivisionError: Occurs when a number is divided by zero.

h
2. NameError: It occurs when a name is not found. It may be local or global.

ik
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.

ha
5. EOFError: It occurs when the end of the file is reached, and yet operations are
being performed.
.S
Problem without handling exceptions
 As we have already discussed, the exception is an abnormal condition that halts the
.A

execution of the program. Consider the following example.


 Example
a = int(input("Enter a:"))
.A

b = int(input("Enter b:"))
c = a/b;
of

print("a/b = %d"%c)
#other code:
Pr

print("Hi I am other part of the program")


 Output:
Enter a:10
Enter b:0
Traceback (most recent call last):
File "exception-test.py", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero

14
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology &amp; Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

Exception handling in python


 If the python program contains suspicious code that may throw the exception, we must
place that code in the try block. The try block must be followed with the except statement
which contains a block of code that will be executed if there is some exception in the try
block.

h
ik
 ha
.S
Syntax
try:
#block of code
.A

except Exception1:
.A

#block of code

except Exception2:
of

#block of code
Pr

#other code
 We can also use the else statement with the try-except statement in which, we can place
the code which will be executed in the scenario if no exception occurs in the try block.
 The syntax to use the else statement with the try-except statement is given below.
try:
#block of code

except Exception1:
#block of code

else:
#this code executes if no except block is executed

15
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology &amp; Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

h
ik
ha
.S
 Example
try:
a = int(input("Enter a:"))
.A

b = int(input("Enter b:"))
c = a/b;
.A

print("a/b = %d"%c)
except Exception:
of

print("can't divide by zero")


else:
Pr

print("Hi I am else block")


 Output:
Enter a:10
Enter b:2
a/b = 5
Hi I am else block
The except statement with no exception
 Python provides the flexibility not to specify the name of exception with the except
statement.
 Consider the following example.
 Example
try:
a = int(input("Enter a:"))

16
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology &amp; Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
 Output:
Enter a:10
Enter b:0
can't divide by zero

Points to remember

h
1. Python facilitates us to not specify the exception with the except statement.

ik
2. We can declare multiple exceptions in the except statement since the try block may
contain the statements which throw the different type of exceptions.

ha
3. We can also specify an else block along with the try-except statement which will be
executed if no exception is raised in the try block.
.S
4. The statements that don't throw the exception should be placed inside the else block.
.A

Declaring multiple exceptions


 The python allows us to declare the multiple exceptions with the except clause. Declaring
multiple exceptions is useful in the cases where a try block throws multiple exceptions.
.A

 Syntax
try:
of

#block of code
Pr

except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)


#block of code
else:
#block of code
 Example
try:
a=10/0;
except ArithmeticError,StandardError:
print "Arithmetic Exception"
else:
print "Successfully Done"
 Output:
Arithmetic Exception
17
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology &amp; Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

The finally block


 We can use the finally block with the try block in which, we can pace the important code
which must be executed before the try statement throws an exception.
 The syntax to use the finally block is given below.
 syntax
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed

h
ik
ha
.S
.A
.A
of
Pr

18
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology &amp; Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

 Example
try:
fileptr = open("file.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")
 Output:

h
file closed
Error

ik
ha
.S
Raising exceptions
 An exception can be raised by using the raise clause in python. The syntax to use the
raise statement is given below.
.A

 syntax
raise Exception_class,<value>
.A

Points to remember
1. To raise an exception, raise statement is used. The exception class name follows it.
of

2. An exception can be provided with a value that can be given in the parenthesis.
3. To access the value "as" keyword is used. "e" is used as a reference variable which stores
Pr

the value of the exception.


Example
try:
age = int(input("Enter the age?"))
if age<18:
raise ValueError;
else:
print("the age is valid")
except ValueError:
print("The age is not valid")
Output:
Enter the age?17
The age is not valid

19
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology &amp; Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM

Example
try:
a = int(input("Enter a?"))
b = int(input("Enter b?"))
if b is 0:
raise ArithmeticError;
else:
print("a/b = ",a/b)
except ArithmeticError:
print("The value of b can't be 0")
Output:
Enter a?10

h
Enter b?0

ik
The value of b can't be 0

ha
.S
Custom Exception
 The python allows us to create our exceptions that can be raised from the program and
caught using the except clause. However, we suggest you read this section after visiting
.A

the Python object and classes.


 Consider the following example.
.A

 Example
class ErrorInCode(Exception):
def __init__(self, data):
of

self.data = data
Pr

def __str__(self):
return repr(self.data)
try:
raise ErrorInCode(2000)
except ErrorInCode as ae:
print("Received error:", ae.data)
 Output:
Received error: 2000

20

You might also like