Changes

Jump to: navigation, search

OPS435 Python Lab 5

544 bytes removed, 01:13, 11 September 2017
PART 1 - Handling Errors
== PART 1 - Handling Errors ==
:According to Wikipedia, Exception Handling There is ''"the process a <u>massive amount</u> of responding to exceptions. On the occurrenceother hand, during computation, of exceptions – anomalous or exceptional conditions requiring special processing – often changing online references can be useful. If you are searching for a specific exception check out the normal flow of program execution."''<br>( [https://endocs.wikipediapython.org/wiki3/Exception_handling) library/exceptions.html#exception-hierarchy Python Exception Documentation.]
:There are a <u>massive amount</u> In this section, we will provide examples of exceptions (way too many how to cover in this course). On the other hand, online references can be useful. If you are searching for handle a specific exception check out the [https://docs.python.org/3/library/few exceptions.html#exception-hierarchy when creating Python Exception Documentationscripts.]
:In this section, we will provide examples of how to handle a few exceptions when creating Python scripts. :'''Perform the Following Steps:'''::#To start, open the ipython3 shell:<source lang="python">ipython3</source>. Before attempting to handle exception errors, let's create an error, and then see how to can "handle" the exception error.it:<br><br>::#Issue the following to create an exception error:<source lang="python">
print('5' + 10)
</source>You should get an exception error similar to the following:<source lang="python">
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
TypeError: Can't convert 'int' object to str implicitly
</source><br>'''Question:''' According to the exception error message, what do you think caused the error?<br><br>
::#Click on the link '[https://docs.python.org/3/library/exceptions.html#concrete-exceptions https://docs.python.org/3/library/exceptions.html#concrete-exceptions.]' and scroll or search for '''TypeError'''. Take a few moments to determine what a ''TypeError'' exception error means.<br><br>You should have learned that the TypeError exception error indicates a mismatch of a type (i.e. string, int, float, list, etc). If Python doesn't know how to handle it, perhaps we could change the number into a string or change the string into a number or at least provide a more user-friendly error message.<br><br>If we don't want the user of our program to have to write this program safelylearn how to read Python exceptions (which is a very good idea), we can catch/trap/handle this error while when it's happeninghappens. This is done with a specific block of code called a [https://docs.python.org/3/tutorial/errors.html#handling-exceptions '''try clause'''] where you place code in-between the '''try:''' and the '''except:''' coding blocks. In a general sense, it works like a modified if-else statement, where the try statement acts as a test, and the except statement will or will not handle the exception depending if it occurs or does NOT occur. That is to say, If no error occurs in the code contained in the '''except''' section, the script will continue as usual but if an error occurs in the except section, then it can be handled with additional coding (like an user-friendly error message).<br>Let's demonstrate to handle our TypeError error by issuing with code that first does not contain an error and then re-issue similar code that DOES generate an error.<br><br>::#Issue the The following code that does NOT generate an error:<source lang="python">
try:
print(5 + 10)
15
</source><br>You should notice that since there was NOT an error, the Python script performed the required task.<br><br>
::#Now, issue the The following code that handles an exception error to provide user-friendly feedback that at least one of the values is not an integer:<source lang="python">
try:
print(5 + 'ten')
At least one of the values is NOT an integer
</source>
::#Let's generate another type of error where we try to open a file that doesn't exist:<source lang="python">
f = open('filethatdoesnotexist', 'r')
</source>
::#Now, to catch and handle this exception error, issue the following lines of code:<source lang="python">
try:
f = open('filethatdoesnotexist', 'r')
print('no file found')
</source><br>Multiple exceptions can also be caught at the same time, such as does not exist, is a directory, or we don't have permission. <br><br>
::#To test out the error handling code (previously issued), try removing permissions from the file, or specify a directory instead of a regular file, and then try to open it:<source lang="python">
try:
f = open('filethatdoesnotexist', 'r')
print('failed to open file')
</source>
::#By taking the time to view the [https://docs.python.org/3/library/exceptions.html#exception-hierarchy Python Exception Hierarchy], you can see how errors get caught in python. The options '''FileNotFoundError''', '''PermissionError''', and '''IsADirectory''' are all inherited from '''OSError'''. 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 exceptions can be performed by issuing the following is with separate <code>except</code> bloks:<source lang="python">
try:
f = open(abc, 'r')
print('unknown error occured')
raise
</source>When catching multiple exceptions, make certain to catch the <u>lowest</u> ones contained in the exception-hierarchy first. 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 attempt to anticipate 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 ===

Navigation menu