My django view goes through a list , uses regex to detect specific elements in the list and finally returns a dict of the contents.
Both IndexError and ValueError can occur while parsing the list.
I need to handle the exceptions in this case.I tried like this
def parse_list(oldlist):
try:
newlist=create_newlist(oldlist)
except Exception as e:
logger.debug(str(e))
else:
mydict = make_dict(newlist)
def create_newlist(oldlist):
mydict = {}
for elem in oldlist:
if re.match('somepattern',elem[0]):
mydict['somekey']=int(elem[0].strip())
else:
raise ValueError(elem[0],' expects an integer')
...
return mydict
Is using the Exception class in except Exception as e: the correct way to handle any exception originating from the above function?
when I wrote a unit test method
def test_me(self):
dl = parse_list(self.somelist)
print 'dl=\n',dl
self.assertTrue(len(dl),0)
I got the console output as
ERROR: test_me (myapp.tests.ParseTest)
..
IndexError: list index out of range
Why is the exception not logged by logger?
When handling exceptions you should try to be as specific as possible. In your case, you should catch
IndexErrorandValueErrorinstead of a generalException:Your other question:
It depends on the configuration of the logger. You’re printing a ‘debug’ message but it could be set to only log/display messages with level ‘error’ or higher. See logging documentation in Python for more information.