Python - Handling Errors like IFERROR

Some easy to use Error handing in Python

I use IFERROR in Excel a lot. We can also do this in Python.

Lines of code 1
Lines of code 2

Let’s say this gives you an error

Python_Iferror_Example.png

What you need to look at is the very last line - ValueError. This is the type of error and changes depending on what went wrong.

So to setup an IFERROR you simply add in a TRY and EXCEPT.

try:

Lines of code 1
Lines of code 2

except IndexError:

print(‘error error’)

Simple as that. If you have multiple errors and you want it to do the same thing for each:

try:

Lines of code 1
Lines of code 2

except (IndexError,ValueError):

print(‘error error’)

If you want something slight different to happen:

try:

Lines of code 1
Lines of code 2

except IndexError:

print(‘error error’)

except ValueError:

print(‘error error error’)

I use this a lot when mining stock data. Some of the stock ID’s are no longer are on Yahoo, so throw up an error. I then want my code to move on to the next section. So I would use something like pass instead of printing error error (assuming whatever error-ed, wouldn’t effect the next lines of the code).

Finally, if you just use Except: any error will be caught. This isn’t usually a good idea as then wild things could end up happening without your knowledge.