Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1 views

Python Chap 6

The document provides an overview of exception handling in programming, detailing the types of errors (syntax and runtime) and the importance of handling exceptions for graceful program termination. It describes the syntax for exception handling using try-except blocks, lists built-in exceptions, and explains how to create user-defined exceptions. Additionally, it covers file handling in Python, including file modes, reading and writing data, and the use of the 'with' statement for automatic file closure.

Uploaded by

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

Python Chap 6

The document provides an overview of exception handling in programming, detailing the types of errors (syntax and runtime) and the importance of handling exceptions for graceful program termination. It describes the syntax for exception handling using try-except blocks, lists built-in exceptions, and explains how to create user-defined exceptions. Additionally, it covers file handling in Python, including file modes, reading and writing data, and the use of the 'with' statement for automatic file closure.

Uploaded by

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

Exception Handling

Some unwanted event that disturbs normal flow of a program is called


as exception.

⮚ In any programming language we have 2 types of errors


⮚ Syntax Errors
⮚ Runtime errors

Syntax Errors:
Errors that occur due to incorrect syntax.
Ex:
x=10
If x==10:
print(“x is 10”) #error (print spelling mistake)

Programmers are responsible for syntactical errors, program runs only


if all the syntactical errors are fixed.
Exception
Handling
Runtime Errors:

⮚ Also called as Exceptions.

⮚ Some unwanted event that disturbs normal flow of a program


is
called as exception.

Ex:
print(10/0) #ZeroDivisionErro
r
print(10/”Ten”) #TypeError

⮚ Exception handling handles only runtime


errors.
Exception Handling
Some of Inbuilt Exceptions:
-------------------------------------

ZeroDivisionError
TypeError
ValueError
FileNotFoundError
EOFError

⮚ Exception handling is done for the graceful termination of the


program.
⮚ Exception handling provides an alternate way of running a
problem normally
Exception
Syntax: Handling
try:
block to check
except:
block to execute if try block fails
⮚ Whenever an exception occurs PVM will create the corresponding
exception object and will check for handling code. If handling code
is not available then Python interpreter terminates the program
abnormally and prints corresponding exception information to the
console and rest of the program won't be executed.

Output:

print(“Hello”) Hello
print(10/0) ZeroDivisionError:
print(“hi”)
Standard Built in exception
Exception
Base class
for all
exceptions

2 StopIteration
Raised when the next() method of an iterator does not point to any object.

3 SystemExit
Raised by the sys.exit() function.

4 StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.

5 ArithmeticError
Base class for all errors that occur for numeric calculation.

6 OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.

7 FloatingPointError
Raised when a floating point calculation fails.
8
ZeroDivisonError
Raised when division or modulo by zero takes place for all numeric types.
9
AssertionError
Raised in case of failure of the Assert statement.
10
AttributeError
Raised in case of failure of attribute reference or assignment.
11
EOFError
Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
12
ImportError
Raised when an import statement fails.
13
KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing
Ctrl+C.
LookupError
Base class for all lookup errors.
15
IndexError
Raised when an index is not found in a sequence.
16
KeyError
Raised when the specified key is not found in the dictionary.
17
NameError
Raised when an identifier is not found in the local or global namespace.
18

EnvironmentError

Base class for all exceptions that occur outside the Python
environment.
20
IOError
Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that
does not exist.
21
OSError
Raised for operating system-related errors.
22
SyntaxError
Raised when there is an error in Python syntax.
23
IndentationError
Raised when indentation is not specified properly.
24
SystemError
Raised when the interpreter finds an internal problem, but when
this error is encountered the Python interpreter does not exit.
Exception Handling
Customized Exception Handling:

try:
block to check
except:
block to execute if try block fails

Ex:

x=10
y=0
try:
print(x/y) Output:
------------
except ZeroDivisionError: cannot divide 10 by 0
print("cannot divide 10 by 0")
Exception Handling
Control flow of try – except block:
---------------------------------------------
try:
statement – 1
statement – 2
statement – 3
except:
statement – 4
statement – 5
else:
statement – 6
Exception
Ex:
Handling
x=int(input("Enter the value of x: "))
Output:
y=int(input("Enter the value of y: "))
Enter the value of x: 4
try: Enter the value of y: 5
sum of x and y is: 9
print("sum of x and y is: ", x+y)
division of x and y is: 0.8
print("division of x and y is: ", x/y) Multiplicatn of x and y is: 20
print("Multiplication of x and y is: ", This is the end of statement
-----------------------------------------
x*y)
Enter the value of x: 4
except: Enter the value of y: 'f'
print("sorry, cannot perform the sorry, cannot perform
operation") the operation
This is the end of statement
print("This is the end of
statement")
Exception
Ex: Handling
import os
try:
print("writing the Risky code")
print(10/20)
os._exit(0)
except:
print("Nothing here") Output:

writing the Risky code


finally: 0.5
print("clean up code")
Exception Handling
else Block with try-except-finally :
⮚ We can use else block with try-except-finally blocks.
⮚ else block will be executed if and only if there are no
exceptions
inside try block.

try:
Risky Code
except:
will be executed if exception inside try
else:
will be executed if there is no exception inside try
finally:
will be executed whether exception raised or not raised and
handled or not handled
Exception
try:
Handling
print("writing the Risky code")

except: Output:
print("Nothing here")
writing the Risky code
nothing went wrong
else: clean up code
print("nothing went wrong")

finally:
print("clean up code")
Exception
try:
Handling
print("writing the Risky code")
print(10/0)
Output:
except:
writing the Risky code
print("Nothing here") nothing went wrong
clean up code
else:
print("nothing went
wrong")
finally:
print("clean up code")
Exception Handling
Types of Exceptions:
In Python there are 2 types of exceptions are possible
⮚ Predefined Exceptions
⮚ User Defined Exceptions

Predefined Exceptions:
⮚ Also known as inbuilt exceptions.
⮚ The exceptions which are raised automatically by Python virtual
machine whenever a particular event occurs are called pre
defined exceptions.
Ex:
ZeroDivisionErro
r TypeError
…..
Exception Handling
User Defined Exceptions:
----------------------------------
⮚ Also known as Customized Exceptions or Programmatic Exceptions
⮚ Based on our requirement, we can define our own exceptions,
such type of programmer defined exceptions are called user
defined exceptions
⮚ Programmer is responsible to define these exceptions and
Python not having any idea about these. Hence we have to raise
explicitly based on our requirement by using "raise" keyword.
Eg:
InSufficientFundsException
InvalidInputException
………
……….
Exception Handling
How to Define and Raise Customized Exceptions:
⮚ Every exception in Python is a class that extends Exception class
either directly or indirectly.

Syntax:
class Classname(predefined exception class name):
def __init__ (self,arg):
self.msg=arg

Ex:
class TooYoungException(Exception):
def __init__ (self,arg):
self.msg=arg

We can raise exception by using raise keyword as follows


raise TooYoungException("message")
Exception
Ex: Handling
class
TooYoungException(Exception):
def __init__(self,arg):
self.msg=arg

class TooOldException(Exception):
def__init__(self,arg):
self.msg=arg

age=int(input("Enter Age:"))
if age>60:
raise TooYoungException("Plz wait some more time you will get
best match soon!!!")
elif age<18:
raise TooOldException("Your age already crossed marriage
age...no chance of getting marriage")
else:
File
Handling
File Handling
⮚ Used for storing date
⮚ As the part of programming requirement, we have to store our data
permanently for future purpose.
⮚ Generally files are used to store less amount of data. For storing the
large volumes of date we should go with databases.
Ex:
if I have to store a the data of 200 students in my class I will go
with file
if I have to store 200000 students data, it will be difficult to store
in a file, so we will go with database
⮚ We have 2 types of files
⮚ Text Files: to store character data
⮚ Binary Files: to store binary data like images, video files, audio files etc..
File Handling
⮚ If we want to perform any operation on a file, first we need to
open
a file.
⮚ In python, if we want to open a file, we need to specify for which
purpose we are opening the file (Ex: reading, writing, appending
etc)

Opening a file:
Python have an inbuilt function for opening a file.
Open()
Syntax:
f = open(‘filename’, ‘mode’)

Ex: f=open(“abc.txt”, ‘r’)


File Handling
List of File modes available in python:
---------------------------------------------

⮚ r 🡪 Opens the file for reading. File must exist; otherwise, it raises
an error.

⮚ w 🡪 Opens the file for writing. Creates a new file or truncates the
existing file.

⮚ a 🡪 Opens the file for appending data. Creates a new file if it


doesn’t exist.
File Handling
⮚ r+ 🡪.Opens the file for both reading and writing. File must exist;
otherwise, it raises an error.
⮚ w+ 🡪 Opens the file for both writing and reading. Creates a new file
or truncates the existing file.
⮚ a+ 🡪 Opens the file for appending and reading. Creates a new file if
it doesn’t exist.

⮚ x 🡪 Creates a new file. Raises an error if the file already exists.

Note: All the modes are for text files only, if we want to use
these
modes for binary files then these should be suffixed with b
Ex: rb, wb, ab, xb
File Handling
⮚ After completing our operations on the file, it is highly recommended to
close the file.
⮚ For closing a file we have an inbuilt method f.close()

Various Properties of File Object:


---------------------------------------------
⮚ Once we open a file and got file object, we can get various details related
to that file by using its properties.

⮚ name: Name of opened file


⮚ mode: Mode in which the file is opened
⮚ closed: Returns boolean value indicates that file is closed or not
⮚ readable(): Returns boolean value indicating whether file is readable or not
⮚ writable(): Returns boolean value indicating whether file is writable or not
File Handling
Ex:

Output:
f=open("abc.txt","w") -----------
print("file Name is: ", f.name) file Name is: abc.txt
print("File Mode is: ", File Mode is: w
is file readable: False
f.mode) is file writable: True
print("is file readable: ", is file closed: False
f.readable()) print("is file writable: ", is file closed: True
f.writable()) print("is file closed: ",
f.closed) f.close()
print("is file closed: ", f.closed)
Ex:2 Output:
f=open("abc1.txt","r") -----------
FileNotFoundError
File Handling
Writing Data to text files:
⮚ We can write character data to the text files by using the following
2
methods.
⮚ write(str)
⮚ writelines(sequence of lines)#sequence may be list/tuple/set

Ex:1
Output:
f=open("C:\\Anand\\abc.txt","w"
-----------
) f.write("Hai this is the first line ") File will be created with Name
f.write("this is the second line abc.txt in the given path
\n") f.write("this is the last line")
First two lines will be copied in
a single line and third will be in
f.close( the second line
)
File Handling
⮚ Write mode always overrides the existing file and that is not good
practice for every scenario, if we want to add the content to the
file with out overriding the file then we should go with append
(“a”)

Ex:2

f=open("C:\\Anand\\abc.txt","w")
l=["Donkey \n","Monkey \n", "Rhino \n"]

f.writelines(["Hai, My Name is \n", "I Teach Python &


Software Testing \n"])
f.writelines(l
) f.close()
File Handling
Reading data from the text file:
⮚ We can read character data from text file by using the following
read
methods.
⮚ read(): To read total data from the file
⮚ read(n): To read 'n' characters from the file
⮚ readline(): To read only one line
⮚ readlines(): To read all lines into a list
Ex: Output:
f=open("C:\\Anand\\abc.txt","r"
Hai, My Name is I Teach Python &
) print(f.read())
Software Testing Donkey
f.close() Monkey
Rhino
File Handling
Ex:2
f=open("C:\\Anand\\abc.txt","r"
Output:
) print(f.read(10))
f.close() Hai, My Na

Ex:3
f=open("C:\\Anand\\abc.txt","r") Output:
print(f.readline())
f.close() Hai, My Name is

Ex:4 Output:
f=open("C:\\Anand\\abc.txt","r"
Hai, My Name is I Teach Python &
) lines=f.readlines() Software Testing Donkey
for line in lines: Monkey
print(line, end=“ ”) Rhino
f.close()
File Handling
The with Statement:
⮚ Every time when ever we open a file, it should be closed at the
end, but if we want to close the file automatically with out using
close method at the end of using a file, then we can go with - with
statement
⮚ The advantage of with statement is it will take care of closing a
file, after completing all operations automatically even in the case
of exceptions also, and we are not required to close explicitly.
⮚ We can use with - statement to group file operation statements
within a block.

Syntax:
with open(‘filename’, ‘mode’) as f:
block of code for operations
File Handling
Ex:

with open('C:\\Anand\\abc.txt', 'w') as f:


f.write("Advanto \n")
f.write("Software \n")
print("is file closed: ", f.closed) #False

print("is file closed: ", #Tru


f.closed) e
File Handling
Inbulit Methods:
-----------------------
tell(): gives the current position of the cursor. Cursor index starts at
zero
Ex:
f= open('C:\\Anand\\abc.txt', 'r')
print(f.tell()) Output:
print(f.read(2)) ------------
print(f.tell()) 0
Ad
print(f.read(5)) 2
print(f.tell()) vant
o7
File Handling
seek(): Used to move cursor (file pointer) to specified
location.
f.seek(offset)
offset: represents the number of positions to jump
data = "Hai, How are you, have a nice
day" f= open('C:\\Anand\\abc.txt', 'w')
Output:
f.write(data) ------------
with open('C:\\Anand\\abc.txt', 'r+') as f:
print(f.read()) Hai, How are you, have a nice
print("current cursor position: ",f.tell()) day current cursor position: 33
f.seek(17) current cursor position: 17
current cursor position: 25
print("current cursor position: ",f.tell())
Hai, How are you, have a Bad
f.seek(25) day!!
print("current cursor position: ",f.tell())
f.write("Bad day!!")
f.seek(0)
Overrides the text from the 25th position
print(f.read()
Only given number of characters will be replaced
File Handling
How to check a particular File exists OR not:
⮚ os library is used to get information about files in our computer.
⮚ os module has path sub module, which contains isFile() function
to check whether a particular file exists or not

Output:
os.path.isfile(fname ------------
) Enter File Name: abc.txt
import os
file with name abc.txt exists
fname = input("Enter File Name: hi how are you
this is a sample file
") if os.path.isfile(fname):
---------------------------------
print("file with
Enter File Name: gxx.txt
name",fname,"exists") file doesn't exists with name
f=open(fname,'r') gxx.txt

print("file doesn't exists with name ", fname)


print(f.read()
File Handling
⮚ Program to print number of lines, words and characters present in the
file.
import os
fname = input("Enter File Name: ")
if os.path.isfile(fname):
print("file with name",fname,"exists")
f=open(fname,'r')

lcount=wcount=ccount=0
for line in f: Output:
lcount=lcount+1 ------------
ccount=ccount+len(line) Enter File Name: abc.txt
words=line.split() file with name abc.txt exists
wcount=wcount+len(words) no of lines: 2
no of words: 9
print("no of lines: ",lcount) no of chars: 36
print("no of words:
",wcount) print("no of chars:
",ccount)
else:
print("file doesn't exists with name ", fname)
File Handling
To change a directory:
import os
os.chdir('C:\\Users\\Veva
Das\\AppData\\Local\\Programs\\Python\\Python37-
32\\anand1')
cwd= os.getcwd()
print("current path: ", cwd)

To remove a

directory import os
cwd= os.rmdir('anand/hai')
print("dir hai deleted successfully")

Note: to delete a directory the directory should be empty.


File Handling
To delete multiple directories:
----------------------------------------
import os
cwd= os.removedirs('anand1/hai/hello')
print("dir hai deleted successfully")

Renaming a directory:
------------------------------
import os
cwd= os.rename('anand', 'python')
print("name changed successfully")
File Handling
To know contents of a directory:
---------------------------------------------
import os
cwd= os.listdir('C:\\Users\\Veva Das\\AppData\\Local\\Programs\\Python\\Python37-
32')
print(cwd)

Or

import os
cwd= os.listdir('.')
print(cwd)

Copying a file:
---------------------
import os
os.popen('copy argv_program.py file6.txt')
File Handling
To display the all contents of a directory:
-------------------------------------------------------

os.walk(path, topdown = True, onerror = None, followlinks =


False)
path : Directory Path
topdown = True : Travel from top to bottom
onerror = None : On error detected which function has to execute.
followlinks = True : To visit directories pointed by symbolic links

import os
forprint("dirpath:
dirpath, dirnames, filenames in os.walk('.'):
", dirpath)
print("dirnames: ", dirnames) Output:
print("filenames: ", ------------
filenames) print() List of all the files and sub files in
the current directory
File Handling
To get the information about the file:
--------------------------------------------------
-import os
print(os.stat('abc.txt') os.stat_result(st_mode=33206,
) st_ino=5910974511095568, st_dev=1620535598,
st_mode: Protection Bits st_nlink=1, st_uid=0, st_gid=0, st_size=37,
st_atime=1575541187,
st_ino: Inode number
st_mtime=1575605235, st_ctime=1575541187)
st_dev: Device
st_nlink: Number of Hard
Links st_uid: User id of Owner
st_gid: Group id of Owner
st_size: Size of File in Bytes
st_atime: Time of Most Recent Access
st_mtime: Time of Most Recent
Modification
st_ctime: Time of Most Recent Meta Data
Change
File Handling
Pickling & Unpickling:
---------------------------
⮚ The process of writing state of object to the file is called pickling
⮚ The process of reading state of an object from the file is called
unpickling
⮚ We can implement pickling and unpickling by using pickle module
of
Python.
⮚ pickle module contains dump() function to perform pickling.
pickle.dump(object,file)
⮚ pickle module contains load() function to perform unpickling
obj=pickle.load(file)
File Handling

.
File Handling
import pickle
class Employee:
def init (self,no,name,sal):
self.no=no
self.name=nam
e
self.sal=sal

def display(self):
withprint(self.no,"\t",self.name,"\t",self.sal
open("emp.txt",'wb') as f:
)
e=Employee(1,"Anand",20000) Output:
pickle.dump(e,f)
File with name emp.txt will be created with
with open("emp.txt",'rb') as f: the details.
obj=pickle.load(f)
print("printing employee printing employee details
details") obj.display() 1 Anand 20000
File Handling
Writing multiple employee objects to a file:
Thank
Q

You might also like