Lecture 22 Slides - Error Handling and Using Files

1 of 17

Error Handling and File Reading

CS 110

1

2 of 17

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):

  • data with the wrong data type (e.g. a string instead of an int), or
  • data that doesn’t make sense for the given context

2

3 of 17

Approach: Use Try/Except

try/except blocks help you handle runtime errors. Basic strategy:

  • Wrap the code that might potentially encounter a runtime error in a “try” block.
  • Write some code to gracefully handle the error in the “except” block.

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

4 of 17

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

5 of 17

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...

6 of 17

Reading from Files

6

7 of 17

Files

  • A way of reading from or writing to permanent storage (secondary memory)
  • A way to conveniently share data from computer to computer (like when you upload your files to Canvas so that we can take a look at them).
  • There are different types of files, each of which has its own way of encoding and storing data.
    • Knowing what kind of file you have gives you a lot of information about how you might want to process the file.
  • We’re mostly going to be talking about how to read and write different kinds of data in files (for data processing tasks).

7

8 of 17

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...

  • .CSV and .TSV files (for storing data)
  • .JPGs, .PNGs, and .GIFs (for pixel color and ordering information)
  • .JSON files: one of many ways to structure and represent information
  • .Python files (.py) (for writing programs)
  • .HTML files (for making web pages)

8

9 of 17

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

10 of 17

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

11 of 17

Example

11

Demo: 00_intro_exercise.py

12 of 17

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

13 of 17

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

14 of 17

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

15 of 17

Useful String Functionality (Methods of Strings)

  • Upper-case and Lower-casemy_string.upper() my_string.lower() "hello".upper() "HELLO".lower()
  • Splitting strings:my_string.split(",") my_string.split(" ") (these are lists!)
  • Joining lists by a string character or characters:", ".join(my_list)
  • Detecting the length of a string:�len(my_string)
  • Indexing a string:my_string[0]
  • Slicing a string:my_string[0:10]

15

16 of 17

Useful List Functionality (List Methods)

  • Detecting the length of a list:�len(my_list)
  • Indexing a list:�my_list[0]
  • Appending an element to a list:�my_list.append("some value")
  • Removing an element from a list (from the end):�my_list.pop()

16

17 of 17

Demos / Challenges

17