Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 9

File and Exceptions

.
File
• Python has a built-in open() function 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.
• File can be open in read mode(r),write(w),append(a),r+(read&
write)
• f = open("test.txt“,’r’)
f.tell() :To find current position
f.seek(0) :To reach desired position
f.readline()
f.read()
f.close()
Exception Handling
• Error in Python can be of two types Syntax
Error and Exceptions.
• Errors are the problems in a program due to
which the program will stop the execution.
• Exceptions occurs during the run time which
interrupts the normal flow of execution of the
program. 
Try and Except Statement

• Try and except statements are used to catch and handle


exceptions in Python.
• Statements that can raise exceptions are kept inside the try clause.
• And the statements that handle the exception are written inside
except clause.
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Exceptions
• NameError :Occurs when a name is not found
globally.
• TypeError: Occurs when an operation or function is
applied to an object of inappropriate type.
• ValueError: occurs for invalid argument value
• ZeroDivision Error: Attempt to divide by zero
• OSError: Error related to I/O or diskfull.
• IndexError: Accessing any invalid index
(LookupError)
Try with Else Clause

• Else clause presents after all the except clause.


• The code enters the else block only if the try clause
does not raise an exception.
def fun(a , b):
    try:
        c = ((a+b) / (a-b))
    except ZeroDivisionError:
        print ("a/b result in 0")
    else:
        print (c)
Finally Keyword
• Python provides a keyword finally which is always executed after
the try and except blocks.
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
Raise keyword
• The raise keyword is used to raise an
exception.
• One can define what kind of error to raise, and
the text to print to the user.
x = -1
if x < 0:
  raise Exception("Sorry, no numbers below
zero")
User Defined Exception

# define Python user-defined exceptions


class Error(Exception):
    #Base class for other exceptions
    pass
 
class zerodivision(Error):
    #Raised when the input value is zero
    pass
 
try:
    i_num = int(input("Enter a number: "))
    if i_num == 0:
        raise zerodivision

except zerodivision:
    print("Input value is zero, try again!")
else:
print()

You might also like