Answer to Question #285019 in Python for kika

Question #285019

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-07T07:45:03-0500

Exceptions are a wonderfully misunderstood thing. They let you know that something has gone wrong and sometimes, what it is that went wrong. At the very least, they give you a stack trace that you can use to figure out what went wrong.

Exceptions help with file errors by reporting them. Let's say your program is designed to load the contents of a file that exists on disk. The problem is, the user did some “spring cleaning" and deleted that file. This file contained the database information that it's supposed to connect to in order to retrieve your companies banking data to issue payroll checks. If the program doesn't report that it can't find that file, it could continue with null data (or worse, random data) leading to your secretary being paid $65,535 this pay period. However, had it reported that it couldn't find the file, things could have been fixed before issues arose.




If we have a program like


try:
    pass
except Exception:
    pass
# else:
#    pass
# finally:
#    pass


if we try to open up a file, say


f = open('testfile.txt')

try:
    pass
except Exception:
    pass
# else:
#    pass
# finally:
#    pass


if we run the above program code, we will have an error display


so, what we will do is to have the modification of the form


 
try:
    f = open('testfile.txt')
except Exception:
    print('_Sorry. This file does not exixt_')
# else:
#    pass
# finally:

# pass

if we then run the above code, we will have the display

Sorry. This file does not exist



So, generally, 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.

Also, handling ValueError exception using try-except block is easily done giving the example:

import math x = int(input('Please enter a positive number:\n')) try: print(f'Square Root of {x} is {math. sqrt(x)}') except ValueError as ve: print(f'You entered {x}, which is not a positive number. ')



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