Understanding ‘try except’ in python
This blog explains the basics of try except using a very simple example.
Consider you have a list of numbers and this list is adulterated with some string value. The task is to ignore the string value and increment all the numbers in the list by 1.
Let’s try to add 1 to each value from the list
You get a TypeError. Let’s try to fix this using try except.
Noicee!! the code works perfectly as expected and doesn’t stop after printing 3 unlike the above code. Now, we can be more specific by also mentioning the respective exception that must be caught so that other errors won’t be skipped.
Let’s consider another example where we again have an adulterated list of numbers. But now the task is to take the reciprocal of the numbers in the list. Let’s add a 0 to the list.
As we are not specific about which exception to catch, the division by zero gets ignored. Now let’s mention we want to only catch the TypeError and see what happens.
Note that there are other ways to solve this task like conditioning on the type of each value in the numbers list.