Join Bill Weinman for an in-depth discussion in this video Handling exceptions, part of Python 3 Essential Training.
Exceptions are a primary method of handling errors in Python. So let's take a look at how we handle exceptions. We will make a working copy of exceptions.py, call it exceptions-working.py. We will open our working copy and here we have a very simple little script that reads lines of text from a file and there is the text file there and it prints them on the screen. Go ahead and we will run this and there is our lines of text. You'll notice, we did this in different way this time.
Instead of using end = a blank string, ctually using the strip method in the string itself and that just strips any trailing new lines from the end of the string. It's another way to do it, using the string method rather than using the print function to resolve that discrepancy. Now if I had typed the name wrong or if I am referring to a file that doesn't exist and I save this and I run it, you'll notice that we get one of Python's lovely little error messages and it has the Traceback (most recent call last).
It's doing what it can to help you to find the error in your code and then down at the bottom here, it says IOError and it has a message. This IOError before the colon is actually the name of the exception. That's the exception that's being raised by the Python interpreter and then after the colon is its error message. Now I can trap that exception. And then I could do something different with it in my code. So here is how I do that. I use try and I am just going to put that line there in the try and then I use except like this, and I can print a message.
I can say, "could not open the file." And then I don't want this to run, so I can put that in the else. Put the else there and so now what I have, I save this and run it. I will just get this little message, "could not open the file, come back tomorrow" and it doesn't try to read the lines in it. And if the typo is not there, I save that and run it, now I get the actual lines of text.
Now this will actually catch any error at all, because I just said except like that. If I want to just kept that particular error, I say except IOError, and if I save that, well let's go ahead and just type this again. Save that, run it, then I get that error. So it's sometimes useful to go ahead and let Python give you that error message, because that's the easy way to find out which error is going to raise. I can also get the error message itself. I can say as e: like this and then instead of come back tomorrow, I can give it that error message like this and then save and run and it says, "Could not open the file: Error 2 No such file or directory:".
And there we have something it's actually useful for the user. Now we can actually if we want to, we can put all of this code up here in the try and it doesn't hurt anything to do it that way and then we don't need an else clause. Save that and run it. We are still getting our error message. Let's go ahead and cut that out and we see that it works the same way. So in the event that you have more than one line of code in your try clause, execution will stop after the error is raised.
So the error gets raised here and then it will go right to handling the error in the except clause. So this line won't get run when the exception happens. So if we have this misspelling in here, you save it and run it, we get the error message and it doesn't try to use the file handle that it never got, because as soon as that exception is raised, which happens in this open function, then the exception clause is run right away. So you'll see this pattern commonly where a number of lines of code will be put in a try block and then in fact sometimes there will be several different except clauses as well, listing out a number of different errors that could be raised.
So this is how exceptions work in Python and this is how you handle exceptions in your code using try and except.
- A Python 3 quick start for experienced developers
- Creating functions and objects
- Using Python's built-in objects and classes
- Repeating code with loops and iterators
- Understanding and using conditional expressions
- Creating sequences with generators
- Reusing code with objects and libraries
- Handling errors with exceptions
Skill Level Beginner
Q: The installation process for the PyDev Eclipse plug-in doesn’t work as described in the videos. What should I do?
A: The version of Eclipse used in the recording of Python 3 Essential Training was Eclipse 3.5.2 (Galileo SR2) and the version of PyDev was 1.5.7. Soon after recording, the Eclipse project was updated to version 3.6, called Helios. As of this writing, the current version of Eclipse is 3.6.1 (Helios SR1).
Around the same time as these updates were being released, the PyDev project was updated as well. As of this writing, the current version of PyDev is 1.6.2. If you are using these most recent versions, the procedure for installing Eclipse itself has not changed, but the process documented in the videos for installing PyDev may not work.
We will be releasing new versions of the videos soon, but the author has posted a document describing the new installation procedure at:
Q: How do you install the pydev-interpreter in Eclipse Indigo on Mac OS X Lion? It's significantly different than what's shown in the video "Installing Python 3 and Eclipse for Mac."
A: Since this course was publishing, there have been upgrades to Mac OS X and Eclipse. In this scenario, after installing Python and Eclipse and the Pydev interpreter, there is a different directory to go to when modifying the preferences. As instructed in the movie (at around 6:40) restart Eclipse and then go to Eclipse > Preferences and drill down to Pydev > Interpreter - Python in the sidebar. Click New and in the Select interpreter dialog that opens, click Browse.
The Open dialog box will open, but does not appear to display your hard drive. You must press and hold the Command+Shift+Period keys. This will display all hidden files on your system. Navigate to the new path ~/Library/Frameworks/Python.framework/versions/3.2/bin/python 3.2 and click Open.
You should be able to proceed normally from there.