Intermediate Python Custom Exceptions
Transcript from the "Custom Exceptions" Lesson
>> Nina: Exceptions are just regular classes the inherit from the exception class. And so I can ask Issubclass(ValueError, Exception). It's true, right? You can do this for all of the exceptions that we've been looking at. So in order to make our own custom exceptions, all we need to do is subclass from exception, just like all these other types of exceptions do.
[00:00:34] So I can say class MyCustomException, subclass from Exception. And then it doesn't really matter. You can even have just pass, which means it's a valid statement in Python, so it means you can kind of have an empty class without any variables or an initializer or anything like that.
>> Nina: Now I can raise this CustomException class by using the raise keyword.
>> Nina: Oops, sorry, no colon there. And now we get a trace back going back to MyCustomException.
>> Nina: This is a really useful way of signaling error conditions in your production Python code. It's good to have custom exception classes so that you can then handle them as specifically as you want in your error checking code.
>> Nina: Does that make sense why? Okay, the nice thing about these custom exception classes is they don't have to get simple. We can get as fancy as we want here. So I'm gonna make a new class. The IncorrectValueError, it's gonna sub class from Exception.
>> Nina: And I'm gonna make a constructor here.
[00:02:11] I'm gonna take self and I'm also gonna take value.
>> Nina: Now I know that exceptions all have a message. I did this by looking at the documentation and you can too, but bear with me for now. I can say that from my error request, I want the message to be got a bad value, and then actually print out what the value was.
>> Nina: How do I call the exception class and pass in my new message?
>> Speaker 2: Super.
>> Nina: Its super.
>> Nina: Then I pass in my new message.
>> Nina: Okay, so now I can say my value equals and if my value is greater than 998,
>> Nina: Oops.
>> Nina: Let me fix that underscore there.
[00:03:18] If my value is greater than 998, raise my IncorrectValueError and pass in my_value.
>> Nina: There we go, that's my error message, right? That looks like the other Python trace backs. It gives us the type and then it gives us the message. So very useful, especially for logging. We can do this because exception in general takes the message.
[00:03:50] So if I wanted to, don't do this.
>> Nina: Not good practice. Just showing you. You generally don't wanna raise the exception because your custom error handling code,
>> Nina: Probably doesn't do a good job of figuring out in why this exception was thrown. But you can pass a message here, you say whatever message I want.
>> Nina: There we go.
>> Nina: Let's write a custom exception for our GitHub API.