Transcript from the "Custom Exception Application" Lesson
>> Nina Zakharenko: Let's write a custom exception for our GitHub API.
>> Nina Zakharenko: I'm gonna make a new class here, or a new Python file here and I'm gonna call it exceptions.py. As you organize your Python code you'll see that this is kind of a common practice of putting a lot of your custom exceptions in an exceptions module.
[00:00:28] So I'm gonna call it GitHubAPIError, usually ending these custom sub-classes an error or exception is the norm, so that you know exactly how to use it. What do I use as the base class?
>> Speaker 2: Exceptions.
>> Nina Zakharenko: Exception,
>> Nina Zakharenko: And I'm gonna have a constructor here and going back to our final exercise, looking here we're raising a RuntimeError, that's not great, right?
[00:01:09] And so one of those built-in exception classes, we're not,
>> Nina Zakharenko: Really doing the right thing cuz all sorts of different other scenarios might cause a run time error.
>> Nina Zakharenko: So, something we might wanna pass in here is this status code that we got back from the API.
>> Nina Zakharenko: Specifically for those in class, because this API has a rate limit.
[00:01:38] We wanna check for 403 to see if that rate limit was reached. And so I'm gonna take a status_code here and then I'm gonna say if my status_code is equal to 403, I'm gonna say my message was, rate limit reached. Otherwise,
>> Nina Zakharenko: Any other type of status code, I'm just gonna say,
>> Nina Zakharenko: The f string the status code was, status code.
>> Speaker 2: You have three s's in the message there.
>> Nina Zakharenko: Thank you. Okay,
>> Nina Zakharenko: Okay, so I'm still missing one thing. What do I have to do to make sure that my message gets passed up to exception?
>> Speaker 3: Call super.
>> Nina Zakharenko: Mm-hm, call super().__init, and pass in our new custom message
>> Nina Zakharenko: And I'm going to run this,
>> Nina Zakharenko: File from with interactive mode, just so I can show you.
>> Nina Zakharenko: Very quickly, intermediate_Python call this file exceptions.py. Okay, so I have my GitHub API here.
>> Nina Zakharenko: And remember we don't just make a new instance of it.
[00:03:17] If you wanna see the exception get raised we use the raised keyword. And if I try not to pass any arguments, we'll see type error that init is missing one required positional argument, the status code, right? So let's say the status code is 500, it'll say GitHubAPIError really helps me narrow it down.
[00:03:37] Status code was 500. What if I pass in a 403 here?
>> Speaker 4: It should say, rate limit reached.
>> Nina Zakharenko: Rate limit reached, yeah. So now we can be a lot more specific and useful.