Error Handling and File Reading
CS 110
1
Handling Runtime Errors
As you may recall, runtime errors typically happen when your program encounters data that was not adequately anticipated by the programmer. Examples of runtime errors include encountering (not an exhaustive list):
2
Approach: Use Try/Except
try/except blocks help you handle runtime errors. Basic strategy:
As you get more experience with programming, you can also catch different types of errors, but that is beyond the scope of this class.
P.S. You always want to use try/except in the "smallest" context possible
3
Try/Except Example
val = "adasdasdasdasdas"
try:
# wrap the "try" block around the thing that may potentially error:
result = int(val)
except:
# write some code that will gracefully handle the error in the event
# that the error happens:
print(val, "cannot be converted to an int!")
4
Try / Except
(THIS IS NOT HOW EXERCISE 7 WORKS)
# This loop keeps going until the user has entered a valid age:
�while True:
age = input("how old are you? ")
try:
age = int(age)
print("Your age is:", age)
break
except:
print("Invalid age. Please enter an integer.")
Code that will execute if there are errors
Code that will ideally execute without errors...
Reading from Files
6
Files
7
File Types
File types are essentially a set of conventions that are followed to encode particular kinds of data. A file extension (e.g. my_code.py, my_text_file.txt, my_image.jpg, etc.) typically indicates what kind of file that you have.
Some file types we’ll be working with include...
8
File and Strings
Much of the work of file processing (and data processing more generally) is parsing and converting data from one format to another. This usually involves multi-step data conversions. For instance:
9
Your program
‘123,55,7\n’
circle(center=(123, 55), 7)
string �(line of the file)
Tuple of ints and int to use with circle function
What does this mean for you?
10
You need to learn some techniques for:
(a) manipulating string data� (b) working with lists� (c) reading and writing files
Example
11
Demo: 00_intro_exercise.py
Reading from Files
f = open("moby_dick.txt", "r")
for line in f:
print(line)
f.close()
12
Indicates that you’re opening the file in ‘read only mode’
Path to your file
Writing to Files
f = open("test.txt", "w")
f.write("hello world!")
f.close()
13
Indicates that you’re opening the file in ‘write mode’
Path to your file
Appending to Files
f = open("moby_dick.txt", "a")
f.write("hello world!")
f.close()
14
Indicates that you’re opening the file in ‘append mode’
Path to your file
Useful String Functionality (Methods of Strings)
15
Useful List Functionality (List Methods)
16
Demos / Challenges
17