Ivan
Ivan

Reputation: 64207

Can Debug.Assert be set to just throw an exception instead of popping up a window in C#?

I'd like an exception to be thrown and the editor to jump to the place whenever an assertion fails in my C# application. But an abort/retry/ignore message box pops up instead. Is there a way to control this behaviour?

Upvotes: 5

Views: 599

Answers (2)

Arafangion
Arafangion

Reputation: 11910

Not directly: That is what Debug.Assert does. See the documentation

http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.aspx

Perhaps you want to use something other than Debug.Assert? Such as simply throwing an exception if it can't be handled, or by invoking some application-defined onError handler when desired?

Alternatively, you may be able to get what you want by adding a listener and hooking into that listener. See the documentation.

Upvotes: 2

TheEvilPenguin
TheEvilPenguin

Reputation: 5672

You could add a custom TraceListener which throws an exception on either of the .Fail() methods:

public class ThrowListener : TextWriterTraceListener
{
    public override void Fail(string message)
    {
        throw new Exception(message);
    }

    public override void Fail(string message, string detailMessage)
    {
        throw new Exception(message);
    }
}

I would probably derive your own Exception type which takes both a message and detailMessage and so it's more obvious where the exception's coming from.

You will have to step up the call stack to the .Assert() call as the debugger will likely take you straight to the throw.

You can add it like this:

Debug.Listeners.Insert(0, new ThrowListener());

Upvotes: 4

Related Questions