Day 27 of 100 - Error Handling

Error Handling Day 3 of 3

Day 27 of 100

Another 3 day code challenge and another new concept. I understand proper error handling is a core Python programming principle but I haven't had much experience with it. I followed the videos and understood what was happening - a way to handle errors within an application without crashing the application. Some really cool and really easy to use features. As a bonus, I learned a lot more about that the error tracebacks mean and how I can improve my code to handle them.

The day 2 and day 3 code challenges were to write error handling for existing applications but I didn't have any that really came to mind so I went looking for some PyBites to help me through and they delivered. I found Bite 10 to be exactly what I was looking for. The challenge was to write a division function and handle errors if it tried to divide by zero or if the quotient was negative. This was a great exercise for a beginner and to solve it, I first had to raise the errors to see what happened under each circumstance.

I found that if I passed a denominator of zero, the function would crash and the traceback said it crashed due to a ZeroDivisionError exception. I added a try block to my function and then added and handled the error by returning 0 if this exception was raised. The second condition took just a little longer to solve because it didn't actually cause the program to crash. Instead it would simply return a quotient with a negative value. I had to look back at the videos and wrote a conditional that looked at the quotient and then raised and exception if it was less than 0. Two fun challenges that were just beyond my ability, making this a challenge while still being fun.

def positive_divide(numerator, denominator):
    try:
        q =  numerator / denominator
    except ZeroDivisionError:
        return 0
    if q < 0:
        raise ValueError
    return q

I will admit that this isn't much code for such an import part of the Python language but this challenge coincided with a very busy time in my day job, which cut my time to work on this down considerably. It should be back to normal soon and allow me to dig back into the challenges to the depth that I was with earlier challenges. On to regular expressions!