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

unit6

This document covers file input/output (I/O) handling and exception handling in Python, detailing how to read and write files, as well as the different modes for file operations. It explains the use of built-in functions for input and output, file handling methods, and the structure of text and binary files. Additionally, it outlines the syntax for various file operations and the importance of closing files after use.

Uploaded by

divyamundlik21
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)
3 views

unit6

This document covers file input/output (I/O) handling and exception handling in Python, detailing how to read and write files, as well as the different modes for file operations. It explains the use of built-in functions for input and output, file handling methods, and the structure of text and binary files. Additionally, it outlines the syntax for various file operations and the importance of closing files after use.

Uploaded by

divyamundlik21
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/ 21

File IO handling and Exception Handling Unit 6

INTRODUCTION
A file is a collection of related data that acts as a container of storage data permanently.
The file processing refers to a process in which a program processes and accesses data stored in files.
A file is a computer resource used for recording data in a computer storage device.
The processing on a file is performed using read/write operations performed by programs.
Python supports file handling and allows users to handle files i.e., to read and write files, along with
many other file handling options, to operate on files.
Python programming provides modules with functions that enable us to manipulate text files and
binary files.
Python allows us to create files, update their contents and also delete files.
A text file is a file that stores information in the term of a sequence of characters (textual
information), while a binary file stores data in the form of bits (Os and 1s) and used to store
information in the form of text, images, audios, videos etc.

I/O OPERATIONS (READING KEYBOARD INPUT, PRINTING TO SCREEN)


In any programming language an interface plays a very important role. It takes data from the user
(input) and displays the output.
One of the essential operations performed in Python language is to provide input values to the
program and output the data produced by the program to a standard output device (monitor).
The output generated is always dependent on the input values that have been provided to the
program. The input can be provided to the program statically and dynamically.
Python language has predefined functions for reading input and displaying output on the screen,
Input can also be provided directly in the program by assigning the values to the variables.
Python language provides numerous built in functions that are readily available to us at Python
prompt.
Some of the functions like input() and print() are widely used for standard Input and Output (1/0)
operations. respectively.

Output (Printing to Screen):


The function print is used to output data to the standard output devices i.e., monitor/screen. The
output can redirect or store on to a file also.
The message can be a string, or any other object. the object will be converted into a string before
written to the screen.

Syntax:
print (object(s),separator=separator, end=end, file=file, Flush= Flush)

Parameter values.

object(s): It can be any object but will be converted to string before printed.
seperator='separator': Optional. Specify how to separate the objects, if there is more than one.
Default is’’ .
end='end’optional. Specify what to print at the end. Default is (line feed).
file= Optional An object with a write method.
File IO handling and Exception Handling Unit 6
flush.: Optional,A.Boolean, specifying if the output is flushed (True) or buffered (False). Default
is False.

Example; For output using print.

print("Hello", "how are you?-, sep=" ---")


Hello ---how are you?
print(10,20,30,sep='-')
10-20-30

To make the output more attractive formatting is used. This can be done by using the str.formatO
method..

Example: For output using format.


>>> a=10
>>> b=20
>>> print('Value of a is 0 and b is 11',format(a,b))
Value of a is 19 and b is 20
>>>print(“I will visit {0} and {1} in summer”,format(‘Jammu,'Kashmir'))
I will visit Jammu and Kashmir in summer

Just like old print style used in C programming language, we can format the output in Python
language also. The % operator is used to accomplish this.

Example: For output with %.


>>> x=12.34567E9
>>> print('The value of x=%3.2f'%x)
The value of x=12.35
>>> print('The value of x=%3.4f'%x)
The value of x=12.3457

The various format symbols available in Python programming are


Sr. No. Format Symbol Conversion

1 %c Character.
2 %s String conversion via strO prior to formatting_
3 %i Signed decimal integer.
4 %d Signed decimal integer.
5 %u Unsigned decimal integer.
6 %o Octal integer.
7 %x Hexadecimal integer (lowercase letters).
8 %X Hexadecimal integer (Uppercase letters).
File IO handling and Exception Handling Unit 6

9 %e Exponential notation (with lowercase 'e').


10 %E Exponential notation (with uppercase E).
11 %f Floating point real number.
12 %g The shorter of %f and %e.
13 %G The shorter of %f and %E.

2 Input (Reading Keyboard Input):


Python provides two built-in functions to read a Line of text from standard input, which by default
comes from the keyboard.
(i) input(prompt): The input(prompt) function allows user input. It takes one argument.
The syntax is as follows:

Syntax; input(prompt)

where. Prompt is a String. Representing a default message before the input.

Example1:For input (prompt) method.

x = input( Enter your name:')


print('Hello, 'x)

output:
Enter your name:abc
Hello, abc.

(ii) input(): The function input always evaluate the input provided by user and return same type
data
The syntax is as follows,
Syntax:
x=input()
If input value is integer type then its return integer value. If input value is string type then its return
string value.
Example: For reading input from keyboard.
>>> x=input()
5
>>> type(x)
<class 'int'›
x=input()
5.6
>>> type(x)
<class '.Float'>
>>> x=int(input())
5
File IO handling and Exception Handling Unit 6
a>> type(x)
<class 'int' >
>> x=float(lnput())
2.5
>>> type(x)
<class ' float' >

File
File is a named location on disk to store related information. It is used to permanently 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 turned
OFF, we use files for future use of the data.
Files are divided into following two categories:-
Text Files: Text files are simple texts in human readable format. A text file is structured as sequence
of lines of text,
Binary Files: Binary files have binary data (Os and is) which is understood by the computer.

When we want to read from or write to a file we need to open it first When we are done,
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:


● Open a file.
● Read or write (perform operation).
● Close the file.
Opening File in different Modes
All files in Python programming are required to be open before some operation (read or write) can
be performed on the file.
In Python programming while opening a file, file object is created, and by using this file object we
can perform different set as operations on the opened file.
Python has a built-in function open() to open a file. This function returns a file object also called a
handle, as it is used to read or modify the file accordingly.
Syntax
file_object = open(file_name, [ access_mode][,buffering])
Parameters.
Filename: The filename argument is a string value that contains the name of the file that we 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. 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 the path is in current working directory, we can just provide the filename, just like in the following
examples:
file=open(“sample.txt")
File IO handling and Exception Handling Unit 6
>>> file_read()
'Hello I am there\n' # content of file
>>>

If the file resides in a directory other than PWD, we have to provide the full path with the file
name:
>>>File=open(“D:\\Files\abc.txt)
>>>File.read()
'Hello I am there’
>>>
We can specify the mode while opening a file. In mode, we specify whether we want to read write
'w' or append 'a' to the file. We also specify if we want to open the file in text mode or binary mode.
The default is reading in text mode. In this mode, we get strings when reading from the file. The
binary mode returns bytes and this is the mode to be used when dealing with non-text files like image
or exe Files.
The mode of the file specifies the possible operations that can be performed on the file what
purpose we are opening a file.

Different Modes of Opening File


Like, C. C++ and Java, a file in a Python programming can be opened in various modes
depending upon the purpose.
For that, the programmer needs to specify the mode whether
● read ‘r'.
● write 'w'.
● or append 'a'

Apart from this, two other modes exist, which specify to open the file in
● text mode or
● Binary mode.
● The text mode returns strings while reading from the file.The default is reading in text
mode.
● The binary mode returns bytes and this is the mode to be used when dealing with non-text
files like image or executable files.
The text and binary modes are used in conjunction with the r, w, and a modes. The list of all the
modes used in Python are given in following table:

Sr.No Mode Description


1 r Opens a file for reading only. The file pointer is placed at the beginning
of the file. This is the default mode.
File IO handling and Exception Handling Unit 6

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 default mode.

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

5 w Opens a rile for writing only. overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.
6 wb Opens a file for writing only irk binary format. Overwrites the file if the
file exists. If the file does not exist, creates a 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 riot 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 a file does not exist. creates a new file for
writing.
9 a. opens a file for appending in binary format. The file pointer Is at the
end of the file. If the file exists That is to be append mode.If the file
does not exit it creates a file for writing.

10 ab opens a file for appending

11 a+ opens a file for both appending and reading

12 ab+ Opens file for both appending and reading in binary format

13 t Opens in text mode

14 b Opens file in binary mode

15 + Opens a file for updating (reading and writing).

Accessing File Contents using Standard Library Functions


Once. a file is opened and we will have one file object we can get various information
related to that. Here. is a list of all attributes related to file object:
File IO handling and Exception Handling Unit 6

Sr.N
o Description Example

1 Returns true if file is rinsed, false otherwise, >>>F=open(“abc.txt”,”w”)


>>> F.closed()
False

2 Returns access mode with which file was opened. >>>F=open((“abc.txt”,”w”)


>>>F.mode
‘w’

3 Returns name of the file, >>>F=open(“abc.txt”,”w”)


>>>F.name
Abc.txt

4 The encoding of the file >>> F=open (“abc.txt”,”w”)


>>>F. encoding
Cp1252

Examples For file object attribute


F=open(“sample.txt”,”r”)
print(F.name)
print(F.mode)
print(f.encoding)
F.close()
Print(f.closed)

Output:
Sample.txt
R
Cp1252
True

Closing File
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.

Syntax: FileObject.close( )

Example: For closing a file.

F=open ( sample. tat")


File IO handling and Exception Handling Unit 6
print("Name of the file: “,F.hame)
f.close()

Output
Name of the File: sample.txt

Writing Data to File


▪ The write method writes any string to an open file. In order to write into a file in Python,
we need to open it in write 'W’. append 'a.' or exclusive creation mode.
▪ The write() method writes the contents onto the file. It takes only one parameter and
returns the number of characters writing to the file.
▪ The writes method is called by the file object onto which we want to write the data We
need to be careful with the 'W mode as it will overwrite into the file if it already exists.
All previous data are erased.
▪ We can use three methods to write to a file in Python namely, write(string) (for
text),write(byte_string) (far binary) and write lines (list).
1. write(string) Method:
The write(string) methodl writes the content of string to the file. returning the number of
characters written,
Example: For write(string) method

f.open("sample.txt”)
print(“content of file”)
print(f.read())
f.open(“sample.-txt",'"w")
f..write(“first line\n”)
f..write(“second line\n”)
f..write(“Third line\n”)
f.close()
f.open("sample.txt”)
print(“content of file”)
print(f.read())

Output:
content of file Hello,1
am There
content of file1. first
line
second line
third line
File IO handling and Exception Handling Unit 6
writelines(list) Method:
It writes a sequence of strings to the file. The sequence can be any iterable object
producing strings. typically a list of strings. There is no return value.

Example: For writeline() method.

fruits=["Orange\n","Banana\n","Apple\n”]
f=open("sample_txt",mode="w")
f.writelines(fruits)
f.close()
f.open("sample_txt",'"r")
print(f.read())

output
Orange
Banana
Apple

Read ( ): Returns the read bytes in the form of a string. Reads n bytes; if n is not specified, then
reads the entire file.
Readline ( ): Reads a line of the file and returns in the form of a string. For specified n, reads at
most n bytes. readline ( ) function does not read more than one line at a time; even if n exceeds, it
reads only one line. Readline ( ) function reads a line of the file and returns it in the string. It takes
an integer value n as a parameter to read the number of characters read at a time. Readline ( ) method
is very efficient in reading the data from a very large file because it fetches the data line by line and
returns and prints on the screen. Readline ( ) returns the next line of the file, which contains a newline
character in the end. Also, if the end of the file is reached, it will return an empty string.
readlines ( ): Reads all the lines and returns them as a string element in a list. Readlines ( ) is used
to read all the lines at a single go and then return them as a string element in a list. This function can
be used for small files, as it reads the whole file content to the memory, then splits it into separate
lines. Using the strip () function, we can iterate over the list and strip the newline ' \n ' character
using the strip ( ) function.

Example: For readline( ) method.


f=open ("sample.txt","r" )
print(f.readline()) # read first line followed by\n
File IO handling and Exception Handling Unit 6
print(f.readline(3))
print(f.readline(5))
print(f.readline())
print(f.readline())

Output:
First
line
Second Line
third Line

readlines():This method maintains a list of each line

Example: For readlines()


f.open(“sample.txt”,”r”)
print(f.readlines())

output:
[ 'first line, 'second line\n', 'third line\n']

File Position
● We can change the current file cursor (position) using the seek0 method. Similarly,
the tell() method returns the current position (in number of bytes) of file
cursor/pointer.
● To change the file object's position use f.seek(offset, reference_point). The position
is computed from adding offset to a reference point.
● The reference point can be omitted and defaults to 0, using the beginning of the file
as the reference point. The reference points are 0 (the beginning of the file and is
default), 1 (the current position of file) and 2 (the end of the file).
● The f.tell() returns an integer giving the file object's current position in the file
represented as number of bytes from the beginning of the file when in binary mode
and an opaque number when in text mode.
In other words, the tell() is used to find the current position of the file pointer in the file while
the seek() is used to move the file pointer to particular position.

Example 11 For file position.


f=open(“sample.txt'',''r")
print(f.tell())
print(f.read())
print(f.tell())
print(f.read())
print(f.seek(0))
File IO handling and Exception Handling Unit 6
print(f.read())

Output:
0
first line
second line
third line
37
0
first line
second line
third line
>>>

Example 2:
fruits=["0range\n'imBanana\n","Apple\e]
f=open("sample_txt",mode"w4-",encodinp"utf-8")
for fru in fruits:
f.write(fru)
print("Tell the byte at which the file cursor is:",f.tell())
f.seek(0)
for line in f:
print(line)

Output:
Tell the byte at which the file cursor is7. 23
Orange Banana Apple

File related standard functions


Sr.No Function Description Example

1 Close the file. We need to reopen


file. close() f.close()
it for further access,
1 f.flush()
2 file.flush() Flush the internal buffer. print(f.read())
f. close()
3 file.fileno() Returns an integer file descriptor. print(f.fileno())

4 file.isatty() It returns true if file has a <tty> print(f.isatty())


attached to it.
File IO handling and Exception Handling Unit 6

try:
Returns the next line from the last while f.next():
5 File.next()
upset Print(f.next)
exception:
This function reads the entire file Lines=f.read()
6 file.read()
and returns a string. f.write(lines)
Lines=f.read(10)
7 file.read(size) Reads the given number of bytes.
print(lines)
file.readline() Reads a single line and returns it Lines=f.readline()
8
as a string. print(lines)
file.readline(size) It will read an entire line (trailing Lines=f.readline(10)
9
with a new line char) from the print(lines)
Reads the content of a file line by lines =f.readlines()
10 file.readlines()
line and returns them as a list of f.writelines(lines)
It calls the readline() to read until text =f.readlines(25)
11 File.readlines(sizehint)
EOF. It returns a list of lines read print(text)
position =f.seek(0,0);
12 file.seek(offset[,from]) Sets the file's current position. print(position)
f.close()
lines =read(10)
13 file.tell() Returns the file's current position. #tell()
print(f.tell())
truncates the file's size. If the f.truncate(10)
14 file.truncate(size)
optional size argument is present, f.close()
It writes a string to the file. And it line ='welcome Geeks\n'
15 file.write(string) f.write(line)
doesn't return any value.
Writes a sequence of strings to f.close()
lines =f.readlines()
16 file.writelines(sequence)
the file. The sequence is possibly f.writelines(lines) f.close()

Example: For file object methods.


f = open(sample,txt","w+")
f.write("Line one\n”,Line two\n”,Line three)
f.seek(0)
print(f.read())
print("Is readable;",f.readable())
pript("Is writeable;",f,writable())
print(“File no:”,f,fileno())
print("is connected to tty-like device:”,f.isatty())
f.truncate(5)
f.flush()
f.c1ose()

Output:
File IO handling and Exception Handling Unit 6
Line one Line two Line three
Is readable! True
Is writeable: True
File no: 3
Is connected to tty-like device: False

Handling Files through OS Module:


The OS module of Python allows us to perform Operating System (OS) dependent operations such
as making a folder, listing contents of a folder. know about a process, end a process etc. It has
methods to view environment variables of the operating system on which Python is working on
and many more.
Directory related Standard Functions:

Sr. Description
Function Example
No

1. os.getcwd() Show current working directory. import os


os..getcwd()

2 os.path.getsize() Show file size in bytes of file passed in size =os.path.getsize("sample . txt")
parameter.

3 os.path.isfile() print(os.path.is.file("sample.trt"))
Is passed parameter a file.

4 os.path.isdir( ) is passed parameter a folder. print(os.path.isdir(“sample_txt"))

5 os.listdir() Print("*Contents of Presentworking directory*”)


os.listdir())
Returns a list of all files and folders of
present working. directory.

6 os .listdir( path) Print("Contents of Present working directory”)


os.listdir(“test.txt))
Return a list containing the names of the
enTries in the directory given by path.

7 os .rename(current, new.) os .rename(“sample.txt”’,”new.txt”)


Rename a file

8
os.remove(flle name) Delete a file. os.remove("sample.txt")
File IO handling and Exception Handling Unit 6
9
0s.mkdir() Creates a single subdirectory. os.madir("testdir")

10 os.chdir(path) Change the current working directory to Os.chdir("d: \IT" )


path.

Example: For handling files through OS module.


import os
os.getcwd()
print(os.path.isfile("sample.txt"))
print(os.path.isdir("sample.txt'))

output
True
False

Renaming a File
Renaming a file in Python is done with the help of the rename() method. To rename a file in Python,
the OS module needs to be imported.The rename() method takes two arguments, the current filename
and the new filename.

Syntax: os.rename(current_file_name, new_file_name)


Example: For remaining files.
import as
os.rename(”sample.txt"„"sample1.txt")

Deleting a File
We can use the remove() method to delete files by supplying the name of the file to be deleted as
the argument.To remove a file, the OS module need to be imported. The remove in Python
programming in used to remove the existing file with the file name.

Syntax:
os.remove(file_name)

Example For deleting files.


import os
os.remove("sample.txt")
File IO handling and Exception Handling Unit 6

The is file0 method in Python programming checks whether the file passed in the method exists or
not. It returns true if the file exist otherwise it returns false.

Directories
If there are a large number of files to handle in the Python program, we can arrange the 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, which
provides us with many useful methods to work with directories (and files as well).

Create New Directory


We can make a new directory using the mk_dir0 method.
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.
Syntax
import os
os.mkdir(testdir”)

Get Current Directory


We can get the present working directory using the getcwd0 method. This method returns the
current working directory in the form of a string.

Example:
>>> import os
>>> os.getcwd()
'C:\users\\ vaishali\\AppData\\Loca1\\Programs\%Python\\Python37-32'

Changing Directory
We can change the current working directory using the chdir() method.The new path that we want
to change must be supplied as a string to this method. We can use both forward slash (F) or the
backward slash (x) to separate path elements.

syntax:
os.chdir("dirname")

Example:
>>> Import os
>>> os.getcwd()
'CA\Users\\vaishali\\AppDataNALocal\\Programs\Wython\Vython371
>>> os.chdir(“d:\IT”)
>>> os.getcwd()
'd:\\IT'

List Directories and Files


All files and sub directories inside a directory can be known using the listdir0 method.
File IO handling and Exception Handling Unit 6
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:
>>> os.listdir()
['DLLs', 'Doc', 'include', 'Lib', 'likes', 'LICENSE„txt', 'NEWS.txtg, 'python.exe', 'python3,d11',
Ppython37.d111, 'oythonw.exe', 'Scripts', itclr„ Ptest.py'„ itestdirl, 'Tends', 'vcruntime140.d111]
RemovingDictionary
The rmdir() method is used to remove directories in the current directory.
Syntax: os rmdir("mydir1")

EXCEPTION HANDILNG
When we execute a Python program, there may be a few uncertain conditions which occur, known
as error. Errors also referred to as bugs that are incorrect or inaccurate action that may cause the
problems in the running of the program or may interrupt the execution of program.

There are following three type of error occurs:

Compile Time Errors: Occurs at the time of compilation, include due error occur to the violation
of syntax roles, like missing of a Color (:)
Run Time Errors: Occurs during the runtime of a program, example, include error occur due to
Wong input submitted to program by user.
Logical Errors: Occurs due to wrong logic written in the program.

● Errors occurs at runtime are known as exception, Errors detected during execution of
program. Python provides a feature. (Exception handling) for handling any unreported
errors in program.
● When exception occurs in the program, execution gets terminated. In such cases we get
system generated error message.
● By handling the exceptions, we can provide a meaningful message to the user about the
problem rather than system generated error message, which may not be understandable to
the user.
● Exception can be either built-in exceptions or user defined exceptions.
● The interpreter or built-in functions cart generate the built-in exceptions while user defined
exceptions are custom exceptions created by the user.

Example: For exceptions.


>>> a=3
>>>if (a<5)
SyntaxError: invalid syntax
>>> 5/0
File IO handling and Exception Handling Unit 6
Traceback (most recent call last):
File "<pyshel#2>", line 1, in <module>
5/0
zerodivisionError: division by zero

Introduction
● An exception is also called as runtime error that can halt the execution of the program.
● An exception is an error that happens/occurs during execution of a program_ When that error
occurs. Python generate an exception that can be handled, which avoids the normal flow of
the program's Instructions.
● Errors detected during execution are called Exceptions. An exception is an event (usually an
error).
● which occurs during the execution of a program that disrupts the normal flow of execution
of the program (or program's instructions).
● In Python programming we can handle exceptions using try-except statement, try-finally
statement and raise statement.

Following table lists all the standard exceptions available in Python programming language:
SR
. Exception Causes of Error
No
1 ArithematicError base class for all errors that occur for numeric calculation.

2 AttributeError Raised in case of failure of attribute reference or assignment,

3 EOFError Raised when there is no input from either the raw_input() or input function and the end of
file Is reached.

4 FloatingPointError Raised,when a floatg point Calculation fails.

5 ImportError Raised when an import statement fails.

6 IndexError Raised when anti index is not found in e sequence.


IOError Raised when an input/ output operation fails, such as the print statement or the open()
7
function when trying to open a file that does not exist.
8 IndentationError Raised when Indentation is not specified priciprly.

9 KeyError Raised when the specifled key Is not found in the dictionary.

10 LookupError Base class for all lookup errors.

11 NameError Raised when an identifier is not found in the local or global namespace.
File IO handling and Exception Handling Unit 6

12 NotImplmentedError Raised when an abstract method that needs to be implemented in an inherited class is not
actually implemented.

13 OverflowError Raised when a calculation exceeds maximum limit for a numeric.

14 OSError Raised for operating system-related errors.

15 RuntimeError Raised when a generated error does not fall into any category.
16 StopIteration Raised when the next method of an iterator does not point to any object.

17 SystemExit Raised by sys.exit()function

StandardError Base class for all built-in exceptions except Stop iteration and SystemExit.
18

19 syntaxError Raised when there is an error in Python syntax.


SystemError Raised when the interpreter finds an internal problem, but when this error is encountered
20
the Python interpreter does not exit

TypeError Raised when an operation or function is attempted that is invalid for the specified data
21 type.

Raised when the built in function for a data type has the valid type of arguments, but the
22 ValueError
arguments have invalid values specified
23 Raised when division or module by zero takes place for all numeric type
ZeroDivisionError

Difference Between Exception and Error


Error: Errors are serious issues that a program should not try to handle. They are usually
problems in the code’s logic or configuration and need to be fixed by the programmer. Examples
include syntax errors and memory errors.
Exception: Exceptions are less severe than errors and can be handled by the program. They
occur due to situations like invalid input, missing files or network issues.

Exception Handling in Python Programming


An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions.
In general, when a Python script encounters a situation that it cannot cope with, it raises an
exception.
When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits.
The exception handling is a process that provides a way to handle exceptions that occur at
runtime. The exception handling is done by writing exception handlers in the program.
For handling exception in Python, the exception handler block needs to be written which
consists of set of statements that need to be executed according to raised exception. There are
three blocks that are used in the exception handling process, namely, try, except and finally.
File IO handling and Exception Handling Unit 6
try, except, else and finally Blocks
try Block: try block lets us test a block of code for errors. Python will “try” to execute the
code in this block. If an exception occurs, execution will immediately jump to the except
block. A critical operation which can raise exception is placed inside the try clause
except Block: except block enables us to handle the error or exception. If the code inside the
try block throws an error, Python jumps to the except block and executes it. We can handle
specific exceptions or use a general except to catch all exceptions.
the code that handles exception is written in except clause
else Block: else block is optional and if included, must follow all except blocks. The else block
runs only if no exceptions are raised in the try block. This is useful for code that should
execute if the try block succeeds.
finally Block: finally block always runs, regardless of whether an exception occurred or not. It
is typically used for cleanup operations (closing files, releasing resources).

The associated except blocks are used to handle any resulting exceptions thrown in the try
block.
If any statement within the try block throws an exception, control immediately shifts to the
catch block. If no exceptions is thrown in the try block, the catch block is skipped.
There can be one or more except blocks. Multiple except blocks with different exception
names can be chained together.
The except blocks are evaluated from top to bottom in the code, but only one except block is
executed for each exception that is thrown.
The first except block that specifies the exact exception name of the thrown exception is
executed. If no except block specifies a matching exception name then an except block that
does not have an exception name is selected, if one is present in the code.
Syntax:
try:
certain operations here
----------------------
except Exceptionl:
If there is Exceptionl, then execute this block.
except Exception2:
If there is Exception2, then execute this block.
--------------------------------
else:
If there is no Exception,then execute this block.

Example: For try statement.


n=10
m=0
try:
a=n/m
except ZeroDivisionError:
print("Divide by zero error")
File IO handling and Exception Handling Unit 6
else:
print (a)
Output:
Divide by zero error

raise Statement
We can raise an existing exception by using raise keyword. So, we just simply write raise
keyword and then the name of the exception. The raise statement allows the programmer to
force a specified exception to occur.
Example: We can use raise to throw an exception if age is less than 18 condition
occurs.
while True:
try:
age = int(input("Enter your age for election: " ) )
if age < 18:
raise Exception
else:
print ("you are eligible for election")
break
except Exception:
print(“This value is too small, try again”)

Output.
Enter your age for election:
This value is too small, try again
Enter your age for election: 18
you are eligible for election

▪ The raise statement can be complemented with a custom exception as explained in next section.
User Defined Exception
Python has many built-in exceptions which forces the program to output an error when
something in it goes wrong. However, sometimes we may need to create custom exceptions
that serves the purpose.
▪ Python allow programmers to create their own exception class_ Exceptions should typically
be derived from the Exception class, either directly or indirectly. I-lost of the built-in
exceptions are also derived from Exception class.
User can also create and raise his/her own exception known as user defined exception.
File IO handling and Exception Handling Unit 6
In the following example, we create custom exception class AgeSmallException that is
derived from the base class Exception.
Example 1: Raise a user defined exception if age is less than 18. 4 define Python user-
defined exceptions

Example1 Raise a user defined exception if age is less than 18.


#define Python user-defined exceptions
class Error(Exception):
# empty class
pass
class AgeSmallException(Error):
# empty class
pass
#main program
while True:
try:
age = int(input("enter age for election"))
if age < 18:
raise AgeSmallException
else:
print( "you are eligible for election")
break
except AgeSmallException:
print( "This value is too small, try again ! " )
print()

Output:
Enter your age for election: 11
This value is too small, try again!
Enter your age for election: 15
This value is too small, try again!
Enter your age for election: 18
You are eligible for election

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