Handling errors with exceptions

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 itexceptions-working.py.So let's go ahead and open our working copy, and we will notice that we have ascript 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 defaulterror messages out to standard error, which is printed in red in Eclipse, butwhat we want to do is want to be able to catch that error and do somethingintelligent within our scripts.We are going to do this with 'try,' and we will go ahead and indent this codeunder 'try' and accept.

Now we will just print, 'something bad happened,' and then we can go ahead andcontinue to execute and say print 'after badness.' And so when we run this, goahead 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 sayexcept IOError as e and I can say something bad happened and put the errormessage in parentheses here.

.format (e)), and when I save that and run it, something bad happened (Error 2 Nosuch file or directory,and now we know exactly what the problem was. We could set a flag. We could meresome different code. We can do anything different that we want to. We have thefull reporting of Python's errors as this variable eSo this is how Python handles errors.It throws these exceptions, and this is how we catch them and how can dosomething intelligent with them.

We will see a lot more examples of this as we go through the rest of the course.

Resume Transcript Auto-Scroll

Author

Released

7/29/2010

Due to its power, simplicity, and complete object model, Python has become the scripting language of choice for many large organizations, including Google, Yahoo, and IBM. In Python 3 Essential Training, Bill Weinman demonstrates how to use Python 3 to create well-designed scripts and maintain existing projects. This course covers the basics of the language syntax and usage, as well as advanced features such as objects, generators, and exceptions. Example projects include a normalized database interface and a complete working CRUD application. Exercise files accompany the course.