Creating Custom Exceptions
00:00 In the previous lesson, I covered some of the more common exceptions that come with Python. In this lesson, I’ll be talking about how to write your own. Everything, including exceptions in Python is an object.
00:13
The built-in exceptions you’ve seen so far all inherit from the Exception
class and there’s no reason you can’t do the same thing. An exception is kind of like a label that explains to other programmers what went wrong.
00:26 So you define your own. If your kind of label gives better information than one of the built in ones. And as it really is just a label mechanism, there isn’t much involved in creating an exception.
00:38
You simply inherit from Exception
and as you don’t have to have any other methods or do anything else to override, it can be an empty class.
00:48
So you can do this using the pass
keyword once more after the REPL. And this time I’m gonna create a custom exception. Yep,
01:03
that’s it. That’s all there is to it. Now I’ve got a new custom exception named GradeValueError
. I can raise instances of it like any other exception.
01:15 I’ll show you how I might use this inside a function that calculates the average of some grades. Along the way,I’ll double check that each grade is a valid number between zero and 100.
01:27
And if not, I’m gonna raise the GradeValueError
. That’s for tracking the total of the grades so I can calculate the average. Then I iterate through the grades passed in.
01:46 For each grade, I check it’s in the valid range.
01:58
And if not, I raise a GradeValueError
with a message explaining what went wrong. Sum the grade up,
02:14 and then calculate the average and return it. Let’s give it a try.
02:23 And how about again, with a bad value?
02:30
And there you go, a GradeValueError
, and that’s how you create and use a custom exception. Kinda like the example in the last lesson, this one could be better as well.
02:41 If I weren’t trying to show you how to write a custom exception, but actually just writing this code, I probably would’ve just used a built-in value error instead. A value error is clear enough and passing the same message that I used here would indicate why it was a value error exception, what the restriction was.
03:01 Of course, if I’d done that, I wouldn’t have been able to show you my custom exception, so hopefully you’ll forgive me. So now you’ve seen some of Python’s exceptions and how to write your own.
03:12
Next up I’ll dive deeper into the attributes of the Exception
class.
Become a Member to join the conversation.