Locating the line number where an exception occurs in python code

前端 未结 10 2038
长情又很酷
长情又很酷 2020-12-16 18:55

I have a code similar to this:

try:
  if x:
      statement1
      statement2
      statement3
  elif y:
      statement4
      statement5
      statement6
          


        
相关标签:
10条回答
  • 2020-12-16 19:17

    we can get the line number by splitting the string state of the traceback.format_exc(). please try running the following code..

    import traceback
    
    try:
        a = "str"
        b = 10
    
        c = a + b
    except Exception as e:
        err_lineno = str(traceback.format_exc()).split(",")[1]
        print(err_lineno)
    

    this will produce the following output

    line 7
    
    0 讨论(0)
  • 2020-12-16 19:19

    If you restructure the code like so, you should get a line number when the exception is raised again:

    except:
        statement7
        raise
    
    0 讨论(0)
  • 2020-12-16 19:20

    Using a general except statement is usually a bad programming practice, so you should specify in your except statement what exception you want to catch. ( like except ValueError: )

    Moreover, you should surround with a try except structure the bits of code that are supposed to be raising an exception.

    0 讨论(0)
  • 2020-12-16 19:23

    I believe the several answers here recommending you manage your try/except blocks more tightly are the answer you're looking for. That's a style thing, not a library thing.

    However, at times we find ourselves in a situation where it's not a style thing, and you really do need the line number to do some other programattic action. If that's what you're asking, you should consider the traceback module. You can extract all the information you need about the most recent exception. The tb_lineno function will return the line number causing the exception.

    >>> import traceback
    >>> dir(traceback)
    ['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_format_final_exc_line', '_print', '_some_str', 'extract_stack', 'extract_tb', 'format_exc', 'format_exception', 'format_exception_only', 'format_list', 'format_stack', 'format_tb', 'linecache', 'print_exc', 'print_exception', 'print_last', 'print_list', 'print_stack', 'print_tb', 'sys', 'tb_lineno', 'types']
    >>> help(traceback.tb_lineno)
    Help on function tb_lineno in module traceback:
    
    tb_lineno(tb)
    Calculate correct line number of traceback given in tb.
    Obsolete in 2.3
    

    Newer versions of the traceback plumbing fix the issue prior to 2.3, allowing the code below to work as it was intended: (this is the "right way")

    import traceback
    import sys
    
    try:
        raise Exception("foo")
    except:
        for frame in traceback.extract_tb(sys.exc_info()[2]):
            fname,lineno,fn,text = frame
            print "Error in %s on line %d" % (fname, lineno)
    
    0 讨论(0)
提交回复
热议问题