When I Catch an Exception, How to Get the Type, File, and Line Number

When I catch an exception, how do I get the type, file, and line number?

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)

Line number in Python exception

import traceback

try:
print("a" + 1)
except Exception as e:
print("There was an error: " + e.args[0] + ". The line where the code failed was " + str(traceback.extract_stack()[-1][1]))

Capture file and line number for an exception that wasn't raised

Here's [a simplified version of] the solution we ultimately went with. It handles caught exceptions as well as passing exception objects directly to add_error().

from inspect import getsourcefile, getfile, getlineno, stack
from sys import exc_info

...

def add_error(self, error):
"""
Adds an error to the test.

:type error: Exception
"""
error.file = None
error.line = None

# Try to guess the file and line number where the error occurred.
exc_tb = exc_info()[2]

try:
if exc_tb:
# If we have traceback info (i.e., from a caught exception), add it to the error.
error.file = (getsourcefile(exc_tb.tb_frame) or getfile(exc_tb.tb_frame))
error.line = getlineno(exc_tb.tb_frame)
else:
#
# Otherwise, find the caller in the current stack.
#
# stack()[1] = (<frame object>, filename, line_number, caller, context_line, pos_in_context_line)
# Note that we pass 0 to `stack()` so that it doesn't return any context lines,
# since we're not interested in that.
#
(error.file, error.line) = stack(0)[1][1:3]
except Exception as e:
# Well, we tried.
error.file = '(unable to determine due to %s %r)' % (e.__class__.__name__, e.message,)
finally:
#
# Very important to make sure `exc_tb` gets deleted to prevent a circular reference. Although Python's GC
# is smart enough to catch this and free the memory anyway, it's better not to create the circular
# reference in the first place.
#
# :see: https://docs.python.org/2/library/sys.html#sys.exc_info
#
del exc_tb

self.errors.append(error)

How can I get the line number where the exception was thrown using Thread.UncaughtExceptionHandler?

Try

e.getStackTrace()[0].getLineNumber();

The first element in the stack trace is the most recently called method (the top of the call stack).

There are also methods to get the class, method and file name.

If the e you get in the UncaughtExceptionHandler does not work well for you (because it wraps the real exception), you can try e.getCause() and look at that stack trace.

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

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

Getting line number from the exception object

The traceback object holds that info in the tb_lineno attribute:

import sys

# ...
except Exception as e:
trace_back = sys.exc_info()[2]
line = trace_back.tb_lineno
raise FlowException("Process Exception in line {}".format(line), e)

How can I get the line number which threw exception?

If you need the line number for more than just the formatted stack trace you get from Exception.StackTrace, you can use the StackTrace class:

try
{
throw new Exception();
}
catch (Exception ex)
{
// Get stack trace for the exception with source file information
var st = new StackTrace(ex, true);
// Get the top stack frame
var frame = st.GetFrame(0);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
}

Note that this will only work if there is a pdb file available for the assembly.

Get file name and line number from Exception

This information is only available if the ".pdb" file for the DLL(s) in question is available.

Therefore, you should ensure that the appropriate ".pdb" files are alongside their corresponding DLLs.

You also need to enable full data in the PDB files. Debug builds do this by default, but release builds do not include the line number information.

You can configure a release build to do so by going to the project's Build page, ensure you have selected the "Release" configuration, then click the "Advanced" button at the bottom of the page. In the "Advanced Build Settings" dialog, you need to select "Full" for the "Debug Info" setting.



Related Topics



Leave a reply



Submit