Introduction
One thing is true: if you ever coded, you faced an error. Period.
Errors are not always a bad thing. I agree that they can drive us mad sometimes, especially if we have looked the code over and over again without finding the bug. However, error messages must be understood as something that is not working as expected in your code.
Let’s face it, we can create N test scenarios, but the end user will find the bug N+1. And that’s ok, as long as we can plan for the most common ones.
In this article, we will go over known Error Handling functions that can keep our code running, even if an error occurs. And we’ll see code snippets for R and Python.
Read on.
Error Handling
Error handling is a programming resource to make your code keep working after finding an error, without breaking.
Imagine that you are writing a function that takes two numbers, calculates the difference between them and return the percent value of the difference compared to the first number. That is a pretty straightforward function, but if you enter a number as string, the code will break and throw an error to the screen: I can’t make math operations with text, buddy.
That is when the error handling can be useful. If we know that this is a common error from the end user side, I can plan to make my code work around that error and return the result even if the numbers were entered as strings.
The programmer can say:
- Try running this piece of code.
- If this does not work and you face an error, run this piece of code instead.
Let’s move on and see how to code that.
Coding
R
In R, the function to be used for error handling is tryCatch
. Like explained before, it will try to run the main code, but if it "catches" an error, the secondary code (the workaround) can run.
Going back to that example in the previous section, a function to calculate percent difference without error handling would be like this.
# Function to calculate the percentage difference between two numbers
pct_difference <- function(n1, n2) {
"Function that takes two numbers and return the percentual difference
between n1 and n2, being n1 the reference number"
pct_diff <- (n1-n2)/n1
return ( cat('The difference between', n1, 'and', n2, 'is', n1-n2,
', which is', pct_diff*100, '% of', n1) )
}
# Test 1
pct_difference(10, 2)
[OUT] The difference between 10 and 2 is 8 , which is 80 % of 10
# Test 2
pct_difference(10, '2')
[OUT] Error in n1 - n2 : non-numeric argument to binary operator
Notice, in Test2, that if we enter a string, the code won’t move forward. It breaks.
Now, we can use tryCatch
and make the function returns the value even if we enter the numbers as string.
# Function to calculate the percentage difference between two numbers
# with error handling
pct_difference_error_handling <- function(n1, n2) {
"Function that takes two numbers and return the percentual difference
between n1 and n2, being n1 the reference number"
# Try the main code
tryCatch(pct_diff <- (n1-n2)/n1,
# If you find an error, use this code instead
error= return(
cat( 'The difference between', as.integer(n1), 'and', as.integer(n2), 'is',
(as.integer(n1)-as.integer(n2)), 'which is',
100*(as.integer(n1)-as.integer(n2))/as.integer(n1),
'% of', n1 )#cat
)#return
)#trycatch
# If no error happens, return this statement
return ( cat('The difference between', n1, 'and', n2, 'is', n1-n2,
', which is', pct_diff*100, '% of', n1) )
}
# Test 1
pct_difference_error_handling(10, 3)
[OUT] The difference between 10 and 3 is 7 which is 70 % of 10
# Test 2
pct_difference_error_handling('10', '3')
[OUT] The difference between 10 and 3 is 7 which is 70 % of 10
Perfect! It worked just fine. Let’s find out how we can do the same code in Python now.
Python
Writing the same function in Python is also very simple. We should use the try ... except
format, in this case. As you may have already concluded, try
the main code snippet, but if an exception (error) occurs, run the secondary code snippet, the workaround.
# Function to calculate the percentage difference between two numbers
# with error handling
def pct_difference_error_handling(n1, n2):
'''Function that takes two numbers and return the percentual difference
between n1 and n2, being n1 the reference number'''
# Try the main code
try:
pct_diff = (n1-n2)/n1
return f'The difference between {n1} and {n2} is {n1-n2}, which is {pct_diff*100}% of {n1}'
# If you find an error, use this code instead
except:
pct_diff = (int(n1)-int(n2))/int(n1)
return f'The difference between {n1} and {n2} is {int(n1)-int(n2)}, which is {pct_diff*100}% of {n1}'
# Test 1
pct_difference_error_handling(10,2)
[OUT] The difference between 10 and 2 is 8, which is 80.0% of 10
# Test2
pct_difference_error_handling('10', '2')
[OUT] The difference between 10 and 2 is 8, which is 80.0% of 10
Very good. Code working properly.
Finally
We could add a finally
clause to any of the functions from both languages. This argument will always run, regardless if the try block raises an error or not. So it could be a completion message or a summary, for example.
try:
print(x)
except:
print("There's no x")
finally:
print("Code ended")
[OUT]
# There's no x
# Code ended
tryCatch( print(x),
error= print('There is no x'),
finally= print('Code ended') )
[OUT]
#[1] "There is no x"
#Error in value[[3L]](cond) : attempt to apply non-function
#[1] "Code ended"
I know these functions are simple and that there would be a much better solution to create them without using error handling. However, I think this was the most gentle way to teach how to write a function with exceptions.
Now, it’s your turn to apply that to your job, in many different use cases and forms to help you solving business problems.
Before You Go
In this quick tutorial, we learned how to handle errors using R or Python.
Error handling is a Programming resource to make your code keep running, even if it finds an expected kind of error. In our example, it was a string input instead of number.
R Error Handling:
- Use the function
tryCatch(expression, error, finally)
In Python:
- Use the function
try: expression except: expression finally: expression
If you liked this content, follow my blog for more.
Find me on LinkedIn too.
Now, I have a Topmate page as well, where you can book some time with me if you’d like to talk about Data Science.
Reference
https://en.wikipedia.org/wiki/Exception_handling
How to Write Your First tryCatch() Function in R – Statology