Watching:

Web Development: Handle Errors with Exceptions in Python 3


show more Handling errors with exceptions provides you with in-depth training on Developer. Taught by Bill Weinman as part of the Python 3 Essential Training show less
please wait ...

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 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.

Handling errors with exceptions
Video duration: 2m 23s 6h 36m Beginner

Viewers:

Handling errors with exceptions provides you with in-depth training on Developer. Taught by Bill Weinman as part of the Python 3 Essential Training

Subjects:
Developer Web
Software:
Python
Author:
please wait ...