i want to create objects in a loop. After the object is created i call methods on these objects. But the creation could fail and so the method call is not possible or even necessary. I want to log the failure, but do not want to stop the loop.
I came up with a stupid example:
import logging
class DivisionCreationError(Exception):
pass
class Division(object):
def __init__(self, a, b):
self.a = a
self.b = b
try:
self.a / self.b
except ZeroDivisionError:
logging.warning('Not possible')
raise DivisionCreationError
else:
self.result = self.a / self.b
def get_result(self):
return self.result
if __name__ == '__main__':
numbers = [(1,2), (1,0), (1,3)]
for i in numbers:
try:
created_object = Division(i[0], i[1])
except DivisionCreationError:
pass
else:
print(created_object.get_result())
This is just an example.
How can i log the failed creation of the objection and still keep the loop running. Is the proceeding in my example okay? I catch an exception and than throw a custom one, which i catch again.
I wouldn't mind if on failure i do not get an object at all and could do something like
for i in numbers:
created_object = Division(i[0], i[1])
if created_object:
print(created_object.get_result())
But could not find a way to do that.
Thank you.