Taohidul Islam
Taohidul Islam

Reputation: 5424

How to get the line number on which exception or error occurred in Python?

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?

Upvotes: 2

Views: 8770

Answers (3)

Taohidul Islam
Taohidul Islam

Reputation: 5424

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())

Upvotes: 1

Lohmar ASHAR
Lohmar ASHAR

Reputation: 1771

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)

Upvotes: 2

sudonym
sudonym

Reputation: 4028

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

Upvotes: 3

Related Questions