Changes

Jump to: navigation, search

OPS435 Python Lab 5

75 bytes removed, 22:25, 5 June 2019
m
INVESTIGATION 2: Exceptions and Error Handling
:So far, you have created Python scripts to prompt a user to input data from the keyboard. When creating Python scripts, you may also need to be able to process large volumes of information, or store processed data for further processing. The first investigation in this lab will focus on file management, opening files, saving data to files, and reading files.
:'''NOTE:''' Since many tasks that system administrators perform deal with files, this is a crucial skill to understand.
:It is very important to provide logic in your Python script in case it '''encounters an error'''. An example would be an invalid path-name or trying to close a file that is already closed. The second investigation in this lab will look into how the Python interpreter '''handle errors''' (commonly referred to as "exception handling") at run time, and learn how to write Python codes code that will run gracefully even when problems occur during program execution.
<blockquote style="margin-left:35px;">{{Admon/caution|style="padding-left:25px"|Risk of Losing File Contents|A common problem that new Python programmers may encounter is to accidentally erase existing contents of a file when writing new data to a file. When opening files for writing (using the ''''w'''' open function option), Python assumes existing content in the file is no longer wanted and it's immediately deleted; therefore, if you wish to write data to a file but keep existing content, you need to use the open file option ''''a'''' (append new data to a file).}}</blockquote>
:#When opening a file for writing, the ''''w'''' option is specified with the '''open()''' function. When the 'w' option is specified - previous (existing) contents content inside the file are is deleted. This deletion takes place the moment the open() function is executed, not when writing to th efilethe file. If the file that is being written to doesn't exist - , the file will be created upon the file opening process.<br><br>:#Create a temporary Python file and in there let's open a non-existent data file (called file1.txt) for writing:<source lang="python">
f = open('file1.txt', 'w')
</source>
= INVESTIGATION 2: Exceptions and Error Handling =
:Running into errors in programming will be a common occurrence. You should expect that it will happen for any code that you write. In python , when an error occurs, the python runtime raises an '''exception'''. This section will teach you to catch these exceptions when they happen and to allow the program to continue running, or to stop program execution with a readable error message.
== PART 1 - Handling Errors ==
</source>You should get an exception error similar to the following:<source>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last) Fiel "<ipython-input-3-1b929b80ca50stdin> ", line 1, in <module>()----> 1 print(TypeError: Can't convert '5int' + 10)object to str implicitly
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 learn how to read Python exceptions (which is a very good idea), we can catch/trap/handle this error when it happens. 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 with code that first does not contain an error and then similar code that DOES generate an error.<br><br>
f.write('hello world\n')
f.close()
except (FileNotFoundError, PermissionError, IsADirectoryIsADirectoryError):
print('failed to open file')
</source>

Navigation menu