Zach Cochran
by Zach Cochran
1 min read

Categories

Tags

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:

def myAge(age):
   return "You were born in {}".format(birthYear(age))

def birthYear(age):
   if age < 0:
       raise BadAgeException("You are not alive!")
   else:
       return 2018 - age

The 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.

In 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:

def myAge(age):
   result = birthYear(age)
   if not result:
       return "You are not alive!"
   else:
       return "You were born in {}".format(result)

def birthYear(age):
   if age < 0:
       return False
   else:
       return 2018 - age

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.

💚