#100DaysOfCode in Python Transcripts
Chapter: Days 25-27: Error handling
Lecture: Concepts: Error handling and exceptions
0:00 Let's quickly review the concepts
0:01 of try and except blocks in Python.
0:05 Python's primary error handling style
0:08 is what's called it's easier to ask
0:10 for forgiveness than permission.
0:13 As opposed to, say, C style of look before you leap.
0:16 In C you check, check, check, check, check,
0:18 and then you just try to do the thing and hope it works.
0:21 Typically what happens when it doesn't work
0:23 is either you get a false sort of return value there
0:26 or just the program just goes away, it's really bad.
0:28 Python is a little bit safer in that
0:30 it's more carefully captures up the errors
0:33 and converts them to exceptions.
0:35 So if it's going to do that anyway,
0:36 let's just try and make it work.
0:38 And if it doesn't work, well,
0:39 we'll catch it and deal with it in that case.
0:40 So it's kind of an optimistic way of handling errors.
0:44 so what we're going to do is we're
0:45 going to say try and do all the stuff,
0:47 and we're going to hope that it all just works
0:49 and kind of assume that it will just go through that block.
0:51 But if it doesn't, we're going to
0:53 drop into one of the specific error handling sections.
0:56 Here we have two possible errors,
0:58 really one that we're dealing with,
0:59 and the rest is kind of a catch all.
1:01 So we're saying except connection error as CE,
1:04 and then we're going to deal with that.
1:06 And in this case we might need to look inside the error
1:09 to see, well, was there a DNS problem,
1:11 is there a network problem,
1:13 did it not respond, things like that,
1:15 did we get a 500 back from the server, all kinds of things.
1:18 So this connection error,
1:19 we're going to catch and deal with that
1:21 and then we do this more general except block
1:24 where here's something we maybe didn't think of,
1:26 we're going to catch that and at
1:27 least try to somewhat not crash.
1:30 As we talked about before, the order matters.
1:31 Most specific goes first, most general last.
1:34 If you get that order wrong,
1:35 you'll never get to your specific errors.
1:37 So most specific, most general.
1:40 This is error handling in Python.