Changes

Jump to: navigation, search

OPS435 Python Lab 5

131 bytes added, 12:30, 5 September 2017
PART 1 - Handling Errors
print('failed to open file')
</source>
::#If you spend some By taking the time looking at to view the [https://docs.python.org/3/library/exceptions.html#exception-hierarchy Python Exception Hierarchy] we , you can see exactly how errors get caught in python. The options '''FileNotFoundError''', '''PermissionError''', and '''IsADirectory ''' are all inherit inherited from '''OSError, this '''. This means that while using more specific errors might be useful for better error messages and handling, it's not always possible to catch every error all the time.::#Another way to catch multiple exceptionscan be performed by issuing the following code:<source lang="python">
try:
f = open(abc, 'r')
print('unknown error occured')
raise
</source>::#When catching multiple exceptions, make sure certain to catch the <u>lowest </u> ones on contained in the exception-hierarchy first. If For example, if you put 'Exception' first, both 'OSError' and 'FileNotFoundError', would never get caught.<br><br>'''TIP::#''' In python it's usually best to 'try:' and 'except:' code rather than to try and determine everything that could go wrong with logic and if statements. For example, instead of checking to see if a file exists and we have read permissions, it can be better to just try and read the file and fail and catch any errors with 'OSError'.
=== Create a Python Script Which Handles Errors ===
13,420
edits

Navigation menu