Python Tutorial: Using Try/Except Blocks for Error Handling

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey how's it going everybody in this video we'll be going over how to handle errors and exceptions in Python by learning how these try/except blocks work now these try/except blocks can be confusing to people who aren't familiar with them because they can actually have a lot of different sections like we have this try except else and finally so let's take a look at exactly what's going on here and how we can use these now a lot of the time we're just going to use these first to try and except so for now I'm going to go ahead and comment out this else and finally so first of all why would we even need a try and except block in the first place well let's run some code that throws an error and it might give us a better idea of why we need this so I'm going to try to open up a file here if we look in the current folder that I'm in we have this test underscore file.txt let's try to open that up and let's accidentally leave off the underscore so if I do test file dot txt without the underscore now if I run this you can see that we get this long trace back error here now this is useful for us as developers because it gives us a lot of useful information we have this line number here and file not found error and exactly what happened but if we get an error like this we wouldn't want something like this to be displayed to the people who are using our software so if we can anticipate sections of our code that might throw an error or an exception then we can use these try and accept blocks to handle them in the way that we want so what I'm going to do here is I'm going to move the code that through the air into this try section here and within this accept block I'm just going to print an error and an exclamation point actually let me make this a little bit more detailed I'm going to say sorry this file does not exist so now if I run this code you can see that we receive our custom error instead of the that longer more verbose error that Python gave us before so what exactly is going on here so what's going on is that within our try block we're going to try to run some code and this throws an exception right here so then if it throws an exception then we go to our accept and then it's going to print out this line here now this exception here is kind of vague now if you remember when we ran this code outside of the try accept block we got a file not found error and we actually want to be as specific as possible when we catch a catch our exceptions because the goal of the Tri accepts isn't to just get around all of the exceptions and errors that we could run into it's meant to catch the errors that we expect and handle them properly so this general exception here it's not only going to catch foul not found errors it's also going to catch a lot of other different problems that we could run into so for example here if I was to make this the correct file name and then a line underneath here let's just make a bad assignment so I'll say far equals bad bar and if I run this you can see that we get the exact same thing it hits this exception and then it says sorry this file does not exist let me fix this little typo here so what happened here is within our try block this code actually ran successfully and this is what threw the exception but that's not clear right now because this is too general so what I'm going to do is I'm going to change this to a catch a file file not found error so now if I save and run this now you can see that we get the regular Python trace back which is a good thing so what happened here is it came in and it opened up this file and that was the error that we were trying to catch and then this was an unexpected exception here and you can see here that it is a name error and we're only catching file not found errors so it didn't get caught and it didn't execute this code here and instead it just printed out the default Python trace back now if we do want to catch more general exceptions then we can actually add another except below this and so if I say except an exception and then within here I'm just going to print let's see I'll just print sorry something went wrong now if you do handle multiple exceptions like this be sure that you are putting the more specific exceptions at the top and the more general ones the further that you go down because if I was to put this general exception here at the top and it's always going to hit that one first and I'll never get to the file not found error now currently we're printing out some custom messages here but if I wanted to just print out the exception that it threw then I can just do as and you can name this whatever I'm just going to say as E and I can print out E and I can also do this for the file not found error - so I'll do as E and instead of this custom message I will print out E and if I run that you can see that it comes down to this exception here and instead of printing out a custom message it prints out the exception that we hit which is the bad far is not defined so if I just get rid of this line of code and then run that then it runs successfully if I give this a bad filename and run that you can see that it says error number two no such file a directory and then the file name okay so that's a quick look at the try except blocks now what's the deal with the else and finally blocks down here so first let's start out with the else and we'll uncomment this now what the else does is it runs code that needs to be executed if the try Clause doesn't raise an exception so so for example here let's say that this didn't run an exception here so I'm going to make this the correct file name and now I'm just going to print out the contents here and then I'm also going to close the file so I'll do an F dot close so if I run this our try isn't going to throw an exception because we have the correct file name here and then since it doesn't throw an exception it's going to execute the code that's within the else clause so it prints out the contents of the file and then it closes the file if I open up this file here you can see that it just says test file contents and that's exactly what got printed out now here now you might wonder why we just didn't put this in our try block so we can move this up here and just execute this underneath and if it throws an exception then hopefully it's one that we'll catch anyway now you could do that but like I was saying earlier that we want to be specific about what it is that we're actually trying to catch here so if I move this code up here then then it may throw an exception and we may catch that exception but it may be something that we weren't trying to catch and it may just be an accident so it's better to just go ahead and put that in the else clause or to just put it after the try block altogether okay so now we come to our finally Clause so like I was saying the else Clause only runs if we don't throw an exception but the finally runs no matter what happens whether the code is successful or whether we throw an exception so this is useful for making sure that you release certain resources regardless of what happened in the triack set so for example say you are working with a database or something like that then this would be an area where you could close down the database at this step so I'm just going to put in a print statement here and I'm just going to say that I am executing the finally so you can see if I run this then it runs our else clause and then it also executes sauer finally and now if within our try if I make something that's going to throw an exception and then I run this you can see that it throws our exception but it also still executes sauer finally so again that's a way that you can make sure that you properly closed down certain things so like you know closing down a database or something like that something that needs to be done regardless if the code is successful or not okay so we're just about done but the last thing that I wanted you to know about exceptions and so you can actually raise exceptions on your own if you need to do that so it doesn't have to be something that Python would have caught on its own so for example here I have this corrupt file txt so if I open up this corrupt underscore file.txt now there's nothing actually wrong with this file but I'm just kind of using it for this example so I want to raise my own exception here so I'm going to say if F dot name is equal to and I'm going to say corrupt file dot txt so I'll copy that and paste it in there now now I'm going to raise an exception manually so to do that it's easy as saying raise and then the exception that you want to raise so I'll just raise this general exception here so if I save that and if I run that so try to print this exception but it just doesn't have any details here so I'll just put in an error with an exclamation point so if I run that again you can see that this line did raise this exception so then it went down to where this except line where we were handling that exception and it printed out the air so this allows us to manually raise exceptions so if I was to comment out that line and run the code now you can see that it did the correct thing that it would have done normally so it opened up the file and it came down here and printed out the contents and close the file the contents of the file it just says corrupt file and then it ran our finally closed so that about does it for this video hopefully it gave you a large overview of exception handling and give you some ideas of how you can use this in your projects if you do have any questions just ask in the comment section below be sure to subscribe for future videos and thank you all for watching
Info
Channel: Corey Schafer
Views: 417,512
Rating: 4.9709921 out of 5
Keywords: Python (Programming Language), Python Tutorial, Python Tutorials, Python for Beginners, Exception Handling, Python Exception, Python Error, Python Exceptions, Python Errors, Python Exception Handling, Python Error Handling, Python Try, Python Try Except, Programming Language (Software Genre), Learn Python, Programming, Programming Tutorials, Computer Science (Field Of Study), Software Engineer (Profession)
Id: NIWwJbo-9_8
Channel Id: undefined
Length: 10min 34sec (634 seconds)
Published: Fri Nov 13 2015
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.