Manish Barnwal

...just another human

Handling errors with try-catch in Python

In the previous post I discuss about how to convert a string to date format in Python. I was working on similar idea today. I had a column of object type which was string of dates. The column name is 'signed_up_at' and I wanted to convert it to date format and then calculate the number of days since the user has signed up on our site.

When I tried to apply this function to create a new column to convert an 'object' type column to date column.

df['date_signed_up'] = df.signed_up_at.apply(lambda x: x.split('T'))

But I got the below error: AttributeError: 'float' object has no attribute 'split'

Which implied that there is a value in 'signed_up_at' column which is float and 'split' doesn't work on float object.

I don't know where this float value is in the column but I can't also apply this 'split' unless I bypass this error.

Comes into picture - try-catch.

Try lets you try a piece of code and when encountered with an error, you can specify what to do with it. Instead of halting completely when encountered with an error, try-except lets you bypass that error and continue the code execution.

Try will try to run a block of code and if it succeeds it won't go to except at all. However, if there is an error in try block, the execution flow goes to except and does what is written in except.

We will do something similar with our error as well.

Advertiser Disclosure: This post contains affiliate links, which means I receive a commission if you make a purchase using this link. Your purchase helps support my work.