import sys, os

try:
    raise NotImplementedError("No error")
except Exception as e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
    print(exc_type, fname, exc_tb.tb_lineno)
Answer from Ants Aasma on Stack Overflow
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 14519177 โ€บ python-exception-handling-line-number
Python exception handling - line number - Stack Overflow
I'm using python to evaluate some measured data. Because of many possible results it is difficult to handle or possible combinations. Sometimes an error happens during the evaluation. It is usually...
Discussions

How to get the error line?
I want to ask in general when I execute small code from the terminal I get the error but I dont know which line cause this error so how I know which line ? Thanks More on discuss.python.org
๐ŸŒ discuss.python.org
12
0
February 9, 2024
Can I use logging to return line number where code failed?
Yes, you can ask it to log exception information, that contains tarceback and line numbers. logging.warning(str_error, exc_info=True) More on reddit.com
๐ŸŒ r/learnpython
3
3
March 26, 2024
Locating the line number where an exception occurs in python code - Stack Overflow
I have a code similar to this: try: if x: statement1 statement2 statement3 elif y: statement4 statement5 statement6 else: raise except: state... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Getting line number from the exception object - Stack Overflow
I have defined a custom Exception object and would like to get the line number of the exception. class FlowException(Exception): pass def something(): print 2/3 print 1/2 print 2/... More on stackoverflow.com
๐ŸŒ stackoverflow.com
January 22, 2018
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ errors.html
8. Errors and Exceptions โ€” Python 3.14.7 documentation
Most exceptions are not handled by programs, however, and result in error messages as shown here: >>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1, in <module> 10 * (1/0) ~^~ ZeroDivisionError: division by zero >>> 4 + spam*3 Traceback (most recent call last): File "<stdin>", line 1, in <module> 4 + spam*3 ^^^^ NameError: name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> '2' + 2 ~~~~^~~ TypeError: can only concatenate str (not "int") to str
๐ŸŒ
Andrew-kirkpatrick
andrew-kirkpatrick.com โ€บ 2019 โ€บ 10 โ€บ get-class-file-and-line-number-from-python-exception
Get class, file and line number from Python Exception using stack frame and traceback โ€“ Andrew Kirkpatrick
To see more than just the string representation of a Python Exception you can get more information from the calling stack frame and traceback using sys.exc_info()
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ python-get-type-file-line-number-of-exception
Python: Get the Type, File and Line Number of Exception | bobbyhadz
April 12, 2024 - Copied!exception type: <class 'ValueError'> exception filename: main.py exception line number: 5 exception message: invalid value
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
How to get the error line? - Python Help - Discussions on Python.org
February 9, 2024 - I want to ask in general when I execute small code from the terminal I get the error but I dont know which line cause this error so how I know which line ? Thanks
๐ŸŒ
YouTube
youtube.com โ€บ sourcegpt
python get line number of exception - YouTube
Download this code from https://codegive.com Certainly! In Python, you can obtain the line number where an exception occurred by using the traceback module. ...
Published: December 19, 2023
Views: 96
Find elsewhere
๐ŸŒ
Bytes
bytes.com โ€บ home โ€บ forum โ€บ topic โ€บ python
Reporting the line number of an exception - Post.Byes
October 31, 2015 - I'm sure this is exceedingly simple but I can't find it anywhere. When I catch an exception I would like to report the line number of the exception as well as the error info. try: someError() except Exception, e: "print_error_an d_line_number" How do I find the line number?
Top answer
1 of 10
21

what about this:

try:
  if x:
      print 'before statement 1'
      statement1
      print 'before statement 2' #ecc. ecc.
      statement2
      statement3
  elif y:
      statement4
      statement5
      statement6
  else:
      raise

except:
      statement7

this is the straightforward workaround but I suggest to use a debugger

or even better, use the sys module :D

try:
      if x:
          print 'before statement 1'
          statement1
          print 'before statement 2' #ecc. ecc.
          statement2
          statement3
      elif y:
          statement4
          statement5
          statement6
      else:
          raise
except:
    print sys.exc_traceback.tb_lineno 
    #this is the line number, but there are also other infos
2 of 10
13

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)
๐ŸŒ
IQCode
iqcode.com โ€บ code โ€บ python โ€บ exception-get-line-number-python
exception get line number python Code Example
October 28, 2021 - import traceback try: print(4/0) except ZeroDivisionError: print(traceback.format_exc())
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-1040.html
line number of exception
I can get error message printed out how to get the line number at which exceptoin occurred: try: stat = callablePy(mainArgv, instGlobalConfig) except Exception as errMsg: printErr('Exception occurred. ') printErr(str(errMsg)) ...
๐ŸŒ
IQCode
iqcode.com โ€บ code โ€บ python โ€บ python-exception-with-line-number
python exception with line number Code Example
October 29, 2021 - try: raise NotImplementedError(&quot;Not implemented&quot;) except Exception as e: exception_type, exception_object, exception_traceback = sys.exc_info() filename = exception_traceback.tb_frame.f_code.co_filename line_number = exception_traceback.tb_lineno print(&quot;Exception type: &quot;, exception_type) print(&quot;File name: &quot;, filename) print(&quot;Line number: &quot;, line_number) ... Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
๐ŸŒ
Inductive Automation
forum.inductiveautomation.com โ€บ ignition
Getting error line number from sys.exc_info - Ignition - Inductive Automation Forum
May 23, 2019 - Hi i've seen other threads recommend providing error reporting using code like; system.gui.errorBox("%s, %s"% (sys.exc_info()[0],sys.exc_info()[1])) But that doesn't provide offending line number which can be very handy. For example the following code: try: # some code except: import sys logger.error(str(sys.exc_info())) outputs: 12:58:53.082 [Thread-31] ERROR com.inductiveautomation.factorypmi.application.script.builtin.WindowUtilities - , getValueAt(): 1s...
๐ŸŒ
Alternetsoft
forum.alternetsoft.com โ€บ alternet studio support
How to find the line number where an exception has occurred for embedded Python interpreter - AlterNET Studio Support - AlterNET Software Forum
January 30, 2024 - Previously we were using the solution provided on this forum for finding the line number by calling Engine.GetService on the IronPython engine. This doesnโ€™t seem to work the same when using the embedded python implementation and when an exception occurs in our code during execution of the ...
๐ŸŒ
DNMTechs
dnmtechs.com โ€บ python-exception-handling-line-number
Python Exception Handling: Line Number โ€“ DNMTechs โ€“ Sharing and Storing Technology Knowledge
In this example, the code inside the try block attempts to divide the number 10 by zero, which raises a ZeroDivisionError. The except block catches this exception and prints an error message along with the exception object. Python provides the traceback module, which offers a set of functions to extract and format stack traces. The stack trace contains information about the sequence of function calls that led to the exception, including the line numbers where each function was called.