close

[Solved] How to handle AssertionError in Python and find out which line or statement it occurred on?

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error How to handle AssertionError in Python and find out which line or statement it occurred on? in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How to handle AssertionError in Python and find out which line or statement it occurred on Error Occurs?

How To Solve handle AssertionError in Python and find out which line or statement it occurred on Error ?

  1. How To Solve handle AssertionError in Python and find out which line or statement it occurred on Error ?

    To Solve handle AssertionError in Python and find out which line or statement it occurred on Error Which gives the following output that includes the offending statement and line number:

  2. How to handle AssertionError in Python and find out which line or statement it occurred on?

    To Solve handle AssertionError in Python and find out which line or statement it occurred on Error Which gives the following output that includes the offending statement and line number:

Solution 1

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That’s all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

Solution 2

Use the traceback module:

import sys
import traceback

try:
    assert True
    assert 7 == 7
    assert 1 == 2
    # many more statements like this
except AssertionError:
    _, _, tb = sys.exc_info()
    traceback.print_tb(tb) # Fixed format
    tb_info = traceback.extract_tb(tb)
    filename, line, func, text = tb_info[-1]

    print('An error occurred on line {} in statement {}'.format(line, text))
    exit(1)

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read