In fact, you are asking two different questions (one in the title, the other at the end).
"How to capture a stack trace?"
Just request the static property System.Environment.StackTrace or through new System.Diagnostics.StackTrace(); .
Reading this property does not require the creation of an exception object at all, so perhaps this is all you need.
"How to initialize the stack trace of the Exception object with the current location?"
The exception object StackTrace property is not initialized until you actually throw the exception object.
"The stack trace is created during the creation of the exception. This is different from Java, where the stack trace is created during the construction of the exception object [& hellip;]." - Standard Standard Infrastructure for Public Languages , chap. 18, p. 301.
Since this property is read-only, you cannot initialize it yourself — unless you get your own exception class:
In combination with the answer to the first question, you can do the following:
OnException(new ExceptionWithPresetStackTrace(System.Environment.StackTrace));
However, this is usually a bad idea, because it allows you to create exception objects that indicate to the developer in any random place (via the StackTrace property), even those where there were virtually no errors. This is misleading and should be avoided.
stakx source share