How to handle exceptions in a list comprehension?
An exception is a runtime anomaly and something which interrupts the flow of the program and sends us an error message. Below mentioned are a few predefined exceptions like ZeroDivisionError, ValueError, KeyboardInterrupt, etc. There are user-defined exceptions also in Python.
Before digging further into the article, we would brush up on a few concepts about list comprehension by referring to this article.
Now that we have a good idea about the working of list comprehensions and exception handling. Let’s now learn about exception handling in List comprehensions. Let us take an example, we have a list of strings named data and each element represents a number.
Our task is to extract numbers from each string from the list data. We can do this by using the below code, where we made use of list comprehension.
But we can clearly see that NA is not a number, the above code throws an exception as the int() function can’t handle this exception. So we’ll now make use of a for loop with a try-except block. But doing this may not always work as we may not know the elements in the list beforehand as we have in these examples. So we have got a better approach i.e. by using the catch() function.
The arguments this catch() function takes in are a function, args, kwargs and a custom exception handler which is optional.
The custom exception handler, by default, returns None.
This is how we can apply the catch() function to our example problem.
The output would be [1,3,5,7,9]