How to catch a python exception in a list comprehension?

PythonServer Side ProgrammingProgramming

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.


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


integer division or modulo by zero
Process finished with exit code 0
Published on 07-Dec-2017 06:56:55