Create a Custom Exception
I don’t like this
AssertionError here. One thing that you can do, because this seems to be a pretty specific codebase that this person is working on, and you can always subclass the built-in
Exception object and just give it a more descriptive name.
You don’t even have to do anything else for a custom exception, but you can just give it a descriptive name. In this case, that could be—we know it’s about
"target" shouldn’t be the same—so the error could be
Okay. And you could pass in the string that I just took out here. You could keep this in there and then it would also appear as an additional context to the
SourceEqualsTargetError. In the terminal, you can see that when I add the string then it also appears in the stack trace, but I don’t really think it’s necessary when we have this custom descriptive name of this exception. Yeah, so the reason why you changed the
AssertionError to the
SourceEqualsTargetError is not only that it’s more descriptive name-wise, but also that the error that was thrown wasn’t an
AssertionError per se.
02:08 Exactly. In Python, generally it’s also okay to raise errors manually, but when you do so, you should know which error to raise. So you don’t want to just raise any error, but you want to be precise about what’s happening there.
02:23 And if you’re unsure about which Python exception you want to raise, then you actually can say, like, “Well, actually, the error that I want to raise is that the source doesn’t equal the target”—or no, that the source equals the target in this case.
Become a Member to join the conversation.