Head First Python

Page 129

files and exceptions

Take a pass on the error With this data (and this program), it is best if you ignore lines that don’t conform to the expected format. If the call to the split() method causes an exception, let’s simply pass on reporting it as an error. When you have a situation where you might be expected to provide code, but don’t need to, use Python’s pass statement (which you can think of as the empty or null statement.) Here’s the pass statement combined with try:

data = open('sketch.txt') for each_line in data: try:

This code is protected from runtime errors.

(role, line_spoken) = each_line.split(':', 1) print(role, end='') print(' said: ', end='') print(line_spoken, end='') except: pass

If a runtime error occurs, this code is executed.

data.close()

Now, no matter what happens when the split() method is invoked, the try statement catches any and all exceptions and handles them by ignoring the error with pass. Let’s see this code in action.

Do this!

Make the required changes to your code in the IDLE edit window.

you are here 4   93


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.