Answer to Question #284637 in Python for Evans Mulenga

Question #284637

Describe how catching exceptions can help with file errors. Write three Python examples that actually generate file errors on your computer and catch the errors with try: except: blocks. Include the code and output for each example in your post.



Describe how you might deal with each error if you were writing a large production program. These descriptions should be general ideas in English, not actual Python code.

1
Expert's answer
2022-01-04T01:09:51-0500
""" Catching exceptions helps a programmer to resolve raised issues at runtime instead of deliberately сlosing their program. There are a lot of types of file errors. e.g. hadware/os errors, name errors, operation errors, data errors. Many of them can be processed in Python as in any other language. """
import os
import errno
import io
import sys
# dirname and filename and path
dn, fn = 'foo', 'bar.txt'
pn = os.path.join(dn, fn)

def pre():
    # https://docs.python.org/3/library/os.html#os.makedirs
    os.makedirs(dn, exist_ok=True)
    # https://docs.python.org/3/library/functions.html?open#open
    # https://docs.python.org/3/library/io.html#io.IOBase.close
    open(pn, 'w').close()

def example1():
    # https://docs.python.org/3/library/os.html#os.mkdir
    try:
        os.mkdir(dn)
    # https://docs.python.org/3/library/exceptions.html#OSError
    except OSError as e:
        # https://docs.python.org/3/library/errno.html
        if e.errno != errno.EEXIST:
            raise
        else:
            print('The directory already exitst')

def example2():
    with open(pn, 'r') as inp:
        try:
            # https://docs.python.org/3/library/io.html#io.TextIOBase.write
            inp.write('test')
        # https://docs.python.org/3/library/io.html#io.UnsupportedOperation
        except io.UnsupportedOperation:
            print('Can\'t change a readonly file')

def example3():
    # not a real example
    with open(pn, 'r') as inp:
        # https://docs.python.org/3/library/sys.html?#sys.stdin
        old = sys.stdin
        sys.stdin = inp
        try:
            # https://docs.python.org/3/library/functions.html#input
            text = input()
        # https://docs.python.org/3/library/exceptions.html#EOFError
        except EOFError:
            print('Unable to read anything')
        finally:
            sys.stdin = old

def post():
    # pn = 'aaa'
    try:
        # https://docs.python.org/3/library/os.html#os.remove
        os.remove(pn)
    except:
        # https://docs.python.org/3/library/sys.html#sys.exc_info
        print(sys.exc_info()[1])
    try:
        # https://docs.python.org/3/library/os.html#os.rmdir
        os.rmdir(dn)
    except:
        print(sys.exc_info()[1])

def main():
    try:
        pre()
        example1()
        example2()
        example3()
    finally:
        post()

if __name__ == '__main__':
    main()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS