How to know the exact line of code where an exception has been caused?
It seems everyone is trying to improve your code to throw exceptions in your code, and no one is attempting the actual question you asked.
Which is because it can't be done. If the code that's throwing the exception is only presented in binary form (e.g. in a LIB or DLL file), then the line number is gone, and there's no way to connect the object to to a line in the source code.
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.
Locating the line number where an exception occurs in python code
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
How to find the exact line that caused an error in C# code?
Have a look at the page "Coding and Debugging the Script Component" on Technet.
In particular, the section "Debugging the Script Component" might give you some pointers:
The Script component does not support the use of breakpoints.
Therefore, you cannot step through your code and examine values as the
package runs. You can monitor the execution of the Script component by
using the following methods:
- Interrupt execution and display a modal message by using the MessageBox.Show method in the System.Windows.Forms namespace. (Remove
this code after you complete the debugging process.)- Raise events for informational messages, warnings, and errors. The FireInformation, FireWarning, and FireError methods display the event
description in the Visual Studio Output window. However, the
FireProgress method, the Console.Write method, and Console.WriteLine
method do not display any information in the Output window. Messages
from the FireProgress event appear on the Progress tab of SSIS
Designer. For more information, see Raising Events in the Script
Component.- Log events or user-defined messages to enabled logging providers. For more information, see Logging in the Script Component.
If you just want to examine the output of a Script component
configured as a source or as a transformation, without saving the data
to a destination, you can stop the data flow with a Row Count
Transformation and attach a data viewer to the output of the Script
component. For information about data viewers, see Debugging Data
Flow.
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)
how to get error line number in C++ program
You are looking for a stack trace and there's no portable way to get it. Something somewhat similar can be achieved with:
struct SourcePoint
{
const char *filename;
int line;
SourcePoint(const char *filename, int line)
: filename(filename), line(line)
{ }
};
std::vector<SourcePoint> callstack;
struct SourcePointMarker
{
SourcePointMarker(const char *filename, int line)
{
callstack.push_back(SourcePoint(filename, line);
}
~SourcePointMarker()
{
callstack.pop_back();
}
}
#define MARK_FUNCTION \
SourcePointMarker sourcepointmarker(__FILE__, __LINE__);
Then right after the beginning of each function (or point of interest) you just add a line... for example
int myFunction(int x)
{
MARK_FUNCTION
...
}
Using this approach in your error handlers you can know who was called by who and so on (of course you will know only functions or places that have been instrumented with MARK_FUNCTION). If this is needed only during testing (and not in production) then probably you should just enable core dumps and learn how to run a debugger in post-mortem analysis.
Getting information about where c++ exceptions are thrown inside of catch block?
This is possible with using SEH (structured exception handling). The point is that MSVC implements C++ exceptions via SEH. On the other hand the pure SEH is much more powerful and flexible.
That's what you should do. Instead of using pure C++ try/catch blocks like this:
try
{
DoSomething();
} catch(MyExc& exc)
{
// process the exception
}
You should wrap the inner code block DoSomething
with the SEH block:
void DoSomething()
{
__try {
DoSomethingInner();
}
__except (DumpExc(GetExceptionInformation()), EXCEPTION_CONTINUE_SEARCH) {
// never get there
}
}
void DumpEx(EXCEPTION_POINTERS* pExc)
{
// Call MiniDumpWriteDump to produce the needed dump file
}
That is, inside the C++ try/catch block we place another raw SEH block, which only dumps all the exceptions without catching them.
See here for an example of using MiniDumpWriteDump.
Finding out the source of an exception in C++ after it is caught?
If you are just interested in where the exception came from, you could just write a simple macro like
#define throwException(message) \
{ \
std::ostringstream oss; \
oss << __FILE __ << " " << __LINE__ << " " \
<< __FUNC__ << " " << message; \
throw std::exception(oss.str().c_str()); \
}
which will add the file name, line number and function name to the exception text (if the compiler provides the respective macros).
Then throw exceptions using
throwException("An unknown enum value has been passed!");
How to know the cause of thrown exception in c++
You can use the Call Stack to see where in your code the program broke.
To display the call stack window, from the menu:
Debug-->Windows-->Call Stack
Then double-click on the top line that corresponds to anything in your own code. This is where your own code made the program break. You can also move to any previous function in the call stack, examine the variables, etc.
In release mode, C++ exceptions do not trace the call stack. You need to design and implement your own exception-handling mechanism.
Related Topics
How to Read Until Eof from Cin in C++
Initializing a Member Array in Constructor Initializer
Multi Line Preprocessor Macros
Why Function Template Cannot Be Partially Specialized
Passing a String Literal as a Type Argument to a Class Template
Convert Cstring to Const Char*
Overload Resolution Between Object, Rvalue Reference, Const Reference
Opencv Get Pixel Channel Value from Mat Image
Is Calling Destructor Manually Always a Sign of Bad Design
Getting Started With Opencv 2.4 and Mingw on Windows 7
How to Parse a Date String into a C++11 Std::Chrono Time_Point or Similar