Poma
Poma

Reputation: 8474

How to capture stack trace?

Sometimes I create an Exception instance without throwing it (for example to pass it directly to handler).

OnException(new AuthorizationException());

How to initialize its stack trace with the current location?

Upvotes: 4

Views: 4637

Answers (3)

You're actually asking two different questions (one in the title, the other at the end).

"How to capture the stack trace?"

Simply by querying the static System.Environment.StackTrace property or via new System.Diagnostics.StackTrace();.

Reading this property does not require you to construct an exception object at all, so perhaps it is all you need.

"How to initialize [an Exception object's] stack trace with current location?"

An exception object's StackTrace property is not initialized until you actually throw the exception object.

"The stack trace is created at the time the exception is thrown. This is in contrast to Java, where the stack trace is created during the construction of the exception object […]."The Common Language Infrastructure Annotated Standard, ch. 18, p. 301.

Since it is a read-only property, you cannot initialize it yourself — unless you derive your own exception class:

// don't do that:
class ExceptionWithPresetStackTrace : System.Exception
{
    public ExceptionWithPresetStackTrace(string stackTrace)
    {
        this.stackTrace = stackTrace;
    }

    public override string StackTrace
    {
        get
        {
            return stackTrace;
        }
    }
    readonly string stackTrace;
}

Combined with the answer to the first question, you could then do this:

OnException(new ExceptionWithPresetStackTrace(System.Environment.StackTrace));

However, this is generally a bad idea because it makes it possible to create exception objects that point the developer at any random location (via the StackTrace property), even ones where no error actually occurred. This is misleading and should be avoided.

Upvotes: 3

Alexander Zbinden
Alexander Zbinden

Reputation: 2541

You can get the current stack trace as a string:

http://msdn.microsoft.com/en-us/library/system.environment.stacktrace.aspx

Upvotes: 0

Alexey Raga
Alexey Raga

Reputation: 7525

You can use Environment.StackTrace property or use StackTrace class:

var stack = new StackTrace();
var data = stack.<whatever you need from it>

But I just have to add: what you do is VERY bad conceptually.

Upvotes: 4

Related Questions