Computer >> Computer tutorials >  >> Programming >> Python

How to catch a python exception in a list comprehension?


There is no built-in function in Python that lets you handle or ignore an exception, so it's not possible to handle all exceptions in a list comprehension because a list comprehension contains one or more expressions; only statements can catch/ignore/handle exceptions.

Delegating the evaluation of the exception-prone sub-expressions to a function, is one feasible workaround; others are checks on values that might raise exceptions.

The way we can handle this issue is using the following code.

 Example

foo = (5,7,1,0,9)
def bar(self):
try:
return [1/i for i in foo]
except ZeroDivisionError as e:
print e
bar(foo)

Output

integer division or modulo by zero
Process finished with exit code 0