All right, you were mentioning that to actually be more close to the question again, you would like to introduce the
except block again. Yeah, and instead of putting it into
validate(), where you’re raising the exception, you generally want to put this exception handling in your main function, so maybe in the top-level function that calls the other functions. As you saw before, like, the exception message bubbles up, so there’s no issue here.
and because we have this nice descriptive error name, we can also be specific about what error that you’d be catching here, so I can say
except SourceEqualsTargetError. Then you want to say
01:19 So this is where you could put the exception handling, not inside of the same function where you’re raising it, but in the calling function, and now your program wouldn’t quit, because You’re catching the exception instead of exiting the program when it gets thrown.
SourceEqualsTargetError got raised, and now in the
main() function, you are handling the error. You’re catching it with the
except statement here and then printing out a different message. In this case,
"Source and target are the same". So one thing that’s a good idea is to actually handle your error that you have because if you would only raise an error and you have this code that we have isolated right now in a bigger application, then your application would crash with this error.
except like Martin did here is a good idea. And then you can do whatever you want with this error. So here in line 12, we just
print("Source and target are the same") and you could do something else.
02:34 So maybe you could ask the user to change the target or change the source to actually make it work. And the other thing which is also important to note is in line 11, to be specific about the error that you want to raise.
So if you only use
except, then maybe
validate() raises another error because your your code is not working, and you just generally print
"Source and target are
the same." And that’s not what you want.
What you want is you want to specifically catch the
SourceEqualsTargetError here and then print this message. So with this code in place, I’m quite happy how everything looks. I don’t know, what do you think, Martin?
03:15 I think I’m happy. I don’t really see anything that bothers me at the moment where I would want to go in and refactor more. So yeah. Perfect. So I would say we are finished with this, and let’s wrap up the course with a summary.
Become a Member to join the conversation.