Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
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.
Get unlimited access to all courses for just $25/month.Become a member
82 Video lessons · 101787 Viewers
61 Video lessons · 88547 Viewers
71 Video lessons · 72357 Viewers
56 Video lessons · 104066 Viewers
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.
Your file was successfully uploaded.