#100DaysOfCode in Python Transcripts
Chapter: Days 25-27: Error handling
Lecture: Demo: try-except blocks

Login or purchase this course to watch this video and the rest of the course contents.
0:00 We've seen that, calling this API, may raise errors. And notice the WiFi being off, pretty much anything we search for is going to result in an error.
0:11 So, we're going to turn the WiFi back on. But before we do, let's convert this full on crash to something we can catch, maybe log,
0:17 send a message to the user. Or we could try again, who knows? Here's how error handling in Python works. What we're going to do is,
0:26 there's a couple options. We could treat this as a separate section. Let's say, this part that actually interacts with the data does the request.
0:34 We're going to treat this as a block that should either work, or not work here. So, we can come up here and type the word try:
0:42 And indent that into the block. Then if something might go wrong, we'll say, except: And I'll say, print Oh, that didn't work.
0:49 And we'll just print that out. Yeah? Now Python says this is a little aggressive, it's too broad, but, that's okay. This is going to work for now,
0:58 and then we'll refine this a little bit. So now if I run it, oh that didn't work. It's a big bad crash, we just say, "You know, that didn't work."
1:07 We could've logged it. We could actually loop around and try again. All sorts of things. But at least we're giving proper feedback to system here.
1:16 Let's turn this back on. WiFi's back. Let's try again. Let's search for capital again. Boom, it's working. Here's how the flow goes.
1:26 We're going to run every function here. And if it succeeds, it's just going to run from here to there and then skip over this except block.
1:35 But if at any step something goes wrong, like, suppose, say right here, this title doesn't exist, and it's going to be an error
1:41 the first time through or something. It's going to immediately stop what it's doing and jump down here. If this throws an error,
1:47 we're not even going to run this prank code. We're just going to jump straight from here to there to deal with it.
1:52 So, we can try some stuff, didn't find anything. Eventually, we'll run into these random errors.
1:58 That one didn't work. So, this is great, but what didn't work? Wouldn't it be nice to know what is going on?
2:05 It turns out there's three or four categories of errors. One of which is the network is down. But there's actually others.
2:11 So, we're going to adjust this to handle these particular errors. So, here's how we can stop the errors from crashing our program.
2:20 But let's see how we can actually deal with the errors in a more fine grained way. One message for say, network errors. Another message for say,
2:28 if you didn't input any keyword to search for.


Talk Python's Mastodon Michael Kennedy's Mastodon