Search code examples
pythondjangotry-except

Print() is never displayed inside python try/Except


I'm working on a Django app.

Somewhere in my code, I use a try/except like this:

for tag in category.get("tags"):
    try:
        newTag, created = MyObject.objects.update_or_create(title=tag.get("title"))
        print("HAHAHA", newTag)
    except:
        pass

It works well, newTag is saved, but print("HAHAHA", newTag) is never rendered. I don't know why.

Please help


Solution

  • Since you're in a Django app, try

    import logging
    ...
    logging.debug('HAHA {}'.format(newTag))
    

    and watch your server logs.

    There lots of additional info on logging in the Django docs, https://docs.djangoproject.com/en/2.0/topics/logging/

    Adding

    It's also a good idea to log exceptions to flush issues out of hiding.

        ...
    except Exception as ex:
        logging.warn("Caught {!r}".format(ex))
    

    The logging module has exception() to help with that, but I prefer having more choice on what level an exception is.