0% found this document useful (0 votes)
74 views9 pages

File and Exceptions

File objects in Python allow reading from and writing to files. The open() function returns a file object that has methods like read(), readline(), seek(), and tell() to interact with the file. Exceptions interrupt normal program flow and can be handled using try and except blocks. Common exceptions include NameError, TypeError, ValueError, and IndexError. An else block runs if no exceptions occur, and finally ensures its code block always runs regardless of exceptions. Users can also define custom exceptions by creating exception classes.

Uploaded by

Vishal Anand
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views9 pages

File and Exceptions

File objects in Python allow reading from and writing to files. The open() function returns a file object that has methods like read(), readline(), seek(), and tell() to interact with the file. Exceptions interrupt normal program flow and can be handled using try and except blocks. Common exceptions include NameError, TypeError, ValueError, and IndexError. An else block runs if no exceptions occur, and finally ensures its code block always runs regardless of exceptions. Users can also define custom exceptions by creating exception classes.

Uploaded by

Vishal Anand
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 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