Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exceptions and files Taken from notes by Dr. Neil Moore

Similar presentations


Presentation on theme: "Exceptions and files Taken from notes by Dr. Neil Moore"— Presentation transcript:

1 Exceptions and files Taken from notes by Dr. Neil Moore
CS 115 Lecture Exceptions and files Taken from notes by Dr. Neil Moore

2 Run-time errors Remember the three types of errors:
Syntax error (code will not run) Run-time error (detected when code runs, crashes) Semantic error (not detected by interpreter, program gives incorrect output or behavior) Another name for a run-time error in Python is an exception. Probably from “the exception, not the rule” Signaling a run-time error is called raising an exception Also called “throwing” an exception (C++ and Java)

3 Exceptions By default, raising an exception crashes your program.
But exceptions can be caught and handled. There are many different kinds of exceptions: TypeError: argument has the wrong type ValueError: argument has a good type but a bad value IndexError: accessing a sequence (a string, a list) out of range ZeroDivisionError: just what it says IOError: file problem, such as “file not found” RuntimeError: “none of the above”

4 Catching exceptions By default, exceptions cause the program to crash.
Because that’s better than continuing to run and doing the wrong thing But sometimes you might have a better idea for how to handle it For example, type-casting a string to int if the string wasn’t numeric, Python can’t give you a number You asked Python to do something and it can’t Exception! But maybe you know what to do in this particular case If it was user input, repeat the input and ask again If it came from a file, maybe ignore that line Maybe the program can use a default value Sometimes you can prevent the exception by checking before you do the action, like comparing a denominator to zero before dividing by it But there are errors that you cannot check for without trying it

5 try/except syntax To catch an exception, you use a try / except statement: try: body that might raise an exception except ExceptionClass: handle the exception code that comes after ExceptionClass is one of that list: ValueError, IOError, etc.

6 try/except semantics If the code in the body raises the specified exception: The body stops executing immediately (like a “goto”) Doesn’t even finish the current line! Then Python runs the except block (instead of crashing) After the body (called the handler) is finished, go on to the code that follows This applies even if the exception is raised inside a function call Exceptions go up the call stack looking for a handler If no handler is found, then the interpreter does its usual error message You can have several except blocks for different exceptions for the same try block. trysqrt.py Or one block for more than one exception: except (ValueError, IndexError):

7 An exception example Back to the numeric input example
Suppose we want to keep asking for a float until we get one So this will be an input validation loop (sentinel logic) We’ll use a flag to mark whether we got a good input while not ok: How do we get the input and convert it to a number? number = float(input(“please enter a number: “)) float(…) raises a ValueError on a non-numeric input So put that line inside a try block If we catch the exception, set the ok flag to False If there was NOT an exception, set the flag to True. Where? In the try body after the input Finally put that whole try/except in two places: Before the loop, and as the last step of the loop When the loop finishes, we know we have a valid number nonnumeric.py

8 Another way Another way to do loops involving an exception
Use a flag like we did before, initialized to False Set the flag to True in the try block as before Put the input try/except inside the loop only Because the flag is False, the loop will run at least once Put the error message in the except So it only happens if there WAS an exception nonnumeric2.py We will use this again when re-prompting for a file

9 Hints for catching exceptions
Have a plan! If you don’t know how to fix the error, don’t catch it It’s better to crash than to continue with bad data Keep the try block as small as possible It should contain the line that might raise the exception And subsequent lines that depend on its success Don’t duplicate code in the try and except blocks That code belongs after the try/except, so it happens either way Don’t wrap the whole main in a try! The program probably won’t know which error happened or how to fix it If you can use it, if is usually simpler If you know in advance what situations will cause an error

10 Dealing with large amounts of data
Some programs need a lot of data. How do you handle it? Hard code it into the source? That’s hard to change if you’re not a programmer Ask the user to type it in each time the program runs? If it’s more than a few pieces, your users will refuse! Or make typos! Store your data in an external file! Can be as big as your device can hold! When you type your program, you save it in a file. Data can be saved too!

11 Why use files to hold data?
They’re easier to edit than a source file Files persist across runs of your program And across reboots of your operating system They can hold LARGE amounts of data (more than will fit in RAM!) You can use the same data file as input for different programs You can use the output of one program as input to another

12 Input/output with the user

13 I/O with files

14 Using files As in other programs (word processors, IDEs, etc.) you must open a file before you can use it in your program. Create a file object in your program that represents the file on disk You can read from or write to the object depending on the mode “r”,”w”,”a” Input or output comes from the file instead of from the user Syntax: fileobj = open(filename, “r”) # r for reading (input) fileobj = open(filename) # default is reading fileobj = open(filename, “w”) # w for writing fileobj is a variable that will hold the file object filename is a string that names the file (can be a constant or a variable)

15 Filenames The default location for a data file is the current directory, i.e., the file your py file is saved in You can specify an absolute path if you want open(“C:\\Users\\me\\input.txt”) Please do not do this (put a path in your open) in your 115 programs. Your TA probably uses different directories than you do.

16 IOError If we are trying to read from a file, what can go wrong?
Maybe the file isn’t there Or it’s there but you don’t have permissions to access it Or you do but then your hard drive crashes In these situations, opening a file raises an IOError exception Renamed to OSError in Python 3.4 You can catch the exception just like any other But there’s no point in trying to open again with the same filename A common fix is to ask the user for another filename

17 Exception while opening
ok = False while not ok: fn = input(“Enter a filename: “) infile = open(fn, “r”) ok = True except IOError: print(“Could not open” , fn)

18 Looping over the lines in a file
The simplest way to use an input file once you have successfully opened it is to loop over the lines in the file A file object can be used as a sequence of lines for a for loop: for line in myfile: Each line is a string delimited by a newline character. myfile is a file object, NOT a filename! Each line ends with the newline character You may need to use strip, rstrip, or split When you’re finished with a file, make sure to close the file! Frees up resources associated with the file If you don’t, the file will take up memory until the program exits … if not longer than that!

19 Text files: what is a line?
So if a text file is a sequence of characters, what’s a line? A sequence of characters delimited by the newline character Newline (‘\n’) is the line delimiter (so it cannot appear in the middle of a line!) (Technically a little more complicated on Windows, but Python hides that) What would two newlines in a row mean? There’s an empty line between them So this file: Hello, world How’s it going? Would look like: Hello, world\n\nHow’s it going?\n

20 Sequential and random access
Sequential access: reading or writing the file in order starting from the beginning and going to the end Similar to how a for loop works on a list or string Read the first line, then the second line, etc. No skipping, no backing up! Random access: reading or writing without regard to order “Go to byte 7563 and put a 7 there” Like lists: we can use mylist[5] without having to go through indexes 0 through 4 first Also called direct access

21 Sequential and random access
Random access does not work that well with text files Bytes don’t always match up with characters And they definitely don’t match up with lines. At what byte number does line 10 start? You’d have to go through the lines sequentially and count Text files usually use sequential access Binary files can use either sequential or random access


Download ppt "Exceptions and files Taken from notes by Dr. Neil Moore"

Similar presentations


Ads by Google