I work with code which looks similar to:
try {
f1();
f2();
f3();
}
catch(Exception) {
//...
}
If in Visual Studio I set a breakpoint within the catch block, is there a way for me to find out which function in the try
block threw the exception?
Removing the try
block to see when the program crashes is not a viable option for me.
The type of the exception does not allow to make a guess easily.
2
Answers
Check the stack trace in the exception object.
You can use the
StackTrace
proprty of theException
:This string will give you the stack of function calls leading to the exception, including the line number for each call. If you have multiple calls to the function throwing the exception, you can find out exactly which call triggered it from the line number.
This is demonstrated in the test below:
Output:
As you can see, the call to
f3
was originated inMain
, line 20 (the call withn
==2).Note:
The output above was acquired from a Debug build. In Release build some information might be missing or inaccurate (due to optimizations etc.).