Exception in Python

How we can catch exceptions in Python?
Here is a short example how we can do it.

#!/usr/bin/python3

def main():
    FileRead()
    DemarcationLine()
    LineStrip()
    DemarcationLine()
    CheckFileExtension()
def ReadFile(filename):
    files = open(filename)
    lines = files.readlines()
    for index, line in enumerate(lines):
        print(index, "=", line)

def StripFile(filename):
    files = open(filename)
    for lines in files:print(lines.strip())


def RaisingError(filename):
    if filename.endswith(".txt"):
        lines = open(filename)
        for line in lines:print(line.strip())
    else:
        raise ValueError("File must end with .txt")

def FileRead():
    try:
        ReadFile("../primary/files.txt") # path is okay, it reads file
    except IOError as e:
        print("Could not open file:", e)

def LineStrip():
    try:
        StripFile("primary/files.txt")
    except IOError as e:
        print("Could not open file:", e) # it will give error


def CheckFileExtension():
    try:
        RaisingError("../primary/file.rtf")
    except IOError as e:
        print("Could not open file:", e)
    except ValueError as e:
        print("Bad Filename:", e)


def DemarcationLine():
    print("******************")

if __name__ == "__main__":
    main()
Advertisements

3 thoughts on “Exception in Python

  1. for some reason your python source is losing its indentation.

    i know of two ways you can fix this: one way is to paste the code in with indents and select with the mouse, and use “preformatted” from the editor toolbar.

    if that did not work, you can write your post, then select the HTML tab at the top of the editor– paste python code with indents and put a

     tag at the top of the code. AFTER the code, put 

    then you can go back to the Visual tab to edit the rest of the post. i hope this helps.

    Liked by 1 person

  2. sorry… the comment ate the PRE tags. what i was trying to say is that you can select the HTML tab at the top of the editor– paste python code with indents and put a <pre> tag at the top of the code. AFTER the code, put </pre>

    then you can go back to the Visual tab to edit the rest of the post.

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s