Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to catch a python exception in a list comprehension?

I have a list comprehension in Python in which an iteration can throw an exception.

For instance, if I have:

foo = (5,7,1,0,9)
[1/i for i in foo]

I'll get an exception while iterating over element ‘0’ of the tuple.

How can I handle this exception and continue execution of the list comprehension?


1 Answer
Rajendra Dharmkar

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):
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
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.