2

I have a Django ORM query like this:

try:
    specialization_object = Specialization.objects.get(name="My Test Specialization")
except Exception as ex:
    print(ex)

When there occurs an exception then it prints "Specialization matching query does not exist.", but it does not print the line number. How can I trace the line number on which the exception or error occurred?

Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39

3 Answers3

3

try this:

import logging
logger = logging.getLogger(__name__)

try:
    specialization_object = Specialization.objects.get(name="My Test Specialization")
except Exception as ex:
    logger.info(ex, exc_info=True) # exc_info will add traceback

further reading see here

sudonym
  • 3,788
  • 4
  • 36
  • 61
2

If you can't for any reason use logging, There's the standard package traceback, and you can do something like:

traceback.print_exc(file=sys.stdout)
Lohmar ASHAR
  • 1,639
  • 14
  • 18
1

I have figured out a simple solution just now:

import traceback
try:
    specialization_object = Specialization.objects.get(name="My Test Specialization")
except Exception as ex:
    print(traceback.format_exc())
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39