1

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?

1 Answer 1

1

Is using the Exception class in except Exception as e: the correct way to handle any exception originating from the above function?

When handling exceptions you should try to be as specific as possible. In your case, you should catch IndexError and ValueError instead of a general Exception:

try:
    ...
except (ValueError, IndexError) as e:
    ...

Your other question:

Why is the exception not logged by logger?

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.