Defining Your Own Exceptions
It is possible to add custom exceptions to your projects. This lesson will show you how to define your own exceptions by inheriting from the Exception
class.
Congratulations, you made it to the end of the course! What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment in the discussion section and let us know.
00:00
The next thing we want to do is we want to know how to define our own exceptions. That could not be easier. All you do is define a class. We’re going to call this NeckbeardException
.
00:13
It’s going to inherit from the Exception
class and it simply passes. Now, other exceptions may have other operations that you may want to care about, maybe logging or something like that, but that’s all you really need to create an exception.
00:29
We’re going to have this raise a NeckbeardException
. Once that happens, we can simply go… We need to make that catch the NeckbeardException
.
00:42
Or we could just do this. We’ll go except
—since we’ve already got so many, let’s keep that trend going.
00:56
We’re going to go ahead and run that. You’ll see that the NeckbeardException
was run and the connection was closed. And then we re-raise the NeckbeardException
, and it just shows you where it came from, which is this particular class.
01:12 And that is how you define your own exception. That being said, defining your own exception is very rarely needed. As you’ll see in the screencast notes, there is a vast number of exceptions that’ll cover almost every type of error, so I suggest you look there first before creating your own.
Stephen on Jan. 11, 2021
Short and sweet and to the point. Thanks.
Walid on Jan. 17, 2021
Dear Madhi, you mentioned that you will leave some material for us! like the list of stdlib exceptions? it is not under supporting material?
![Avatar image for Bartosz Zaczyński](/cdn-cgi/image/width=500,height=500,fit=crop,gravity=auto,format=auto/https://files.realpython.com/media/coders_lab_2109368.259b1599fbee.jpg)
Bartosz Zaczyński RP Team on Jan. 18, 2021
@Walid You’ll find all information about the built-in exceptions in Python in the official documentation. Scroll down to the very bottom for a quick reference of the entire exception hierarchy if you don’t want to read the descriptions of the individual classes.
Walid on Jan. 18, 2021
Thank you @Bartosz
Become a Member to join the conversation.
Ghani on Oct. 24, 2020
Good course; Thanks!