Join Bill Weinman for an in-depth discussion in this video Handling errors with exceptions, part of Python 3 Essential Training.
- View Offline
Error reporting in Python is done with something called exceptions. Exceptions are an object- oriented way of handling errors. So let's take a look how this works in Python. Go ahead and make a working copy of exceptions.py. We'll call it exceptions-working.py. So let's go ahead and open our working copy, and we will notice that we have a script here that opens a file and reads the lines and prints the lines.
The problem is is that it's spelled the filename wrong, and so when we run this, we will get an error, and we see there is the error. And you will notice that error is in red. That's because Python sends its default error messages out to standard error, which is printed in red in Eclipse, but what we want to do is want to be able to catch that error and do something intelligent within our scripts. We are going to do this with 'try,' and we will go ahead and indent this code under 'try' and accept.
Now we will just print, 'something bad happened,' and then we can go ahead and continue to execute and say print 'after badness.' And so when we run this, go ahead and save it and run it, something bad happened and after badness. We can see that we caught the error, we did something, and we continued after that. Now we actually print the error message that Python gives us. We can say except IOError as e and I can say something bad happened and put the error message in parentheses here.
.format (e)), and when I save that and run it, something bad happened (Error 2 No such file or directory, and now we know exactly what the problem was. We could set a flag. We could mere some different code. We can do anything different that we want to. We have the full reporting of Python's errors as this variable e So this is how Python handles errors. It throws these exceptions, and this is how we catch them and how can do something intelligent with them.
We will see a lot more examples of this as we go through the rest of the course.
- 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