TIL: Python Exceptions From Functions
Wasn’t really sure what to call this, but it’s something neat and also something that really shows just why using exceptions is so much better than returning back some other junk.
Let’s suppose that I have the following code:
myAge function turns around and makes a call to the
birthYear function, which it relies on for completing its task of printing out your birth year based on the number you provided.
birthYear we do a check to see if age is less than 0. If it is, we go ahead and throw our custom exception. When this exception is thrown, it goes straight back to whomever initially called the
myAge function. So without any work on your part, that exception message will be handled inside of
myAge and get right back to where it needs to be going!
That’s super cool, because the alternative is a lot more work. If I were to do the above the way that I used to do things, it would look like the following:
You then have to add logic to your initial function in order to handle this negative case that gets returned to you, just so that you can handle the response message back. The other alternative is setting to pass back whatever you get to the calling party, but then they have to know what to put in their code to handle your various responses.
Exceptions are your friend.