tags:

views:

78

answers:

2

Hi folks,

I'd like to know if there is a way to throw an Exception from inside a function, but to not include that function in the exception stack trace. E.g.

void ThrowException()
{
    throw Exeption();
}

And then, if I call that function from a function called foo() I want the exception stack trace to start with at foo(), not at ThrowException(). I assume if this was possible it might be through the use of attributes on the method.

I'm interested in the general answer, but in case this isn't possible, what I'm really trying to do is create an extension method AssertEqual() for IEnumerable that I'll use in NUnit tests. So when I call MyEnumerable.AssertEqual(otherEnumerable) and it fails, NUnit should report the error inside the test function, not inside the extension method.

Thanks!

+2  A: 

Maybe you could derive your own exception type and override the StackTrace property getter to exclude your method:

using System;
using System.Collections.Generic;

class MyException : Exception {

    string _excludeFromStackTrace;

    public MyException(string excludeFromStackTrace) {
        _excludeFromStackTrace = excludeFromStackTrace;
    }

    public override string StackTrace {
        get {
            List<string> stackTrace = new List<string>();
            stackTrace.AddRange(base.StackTrace.Split(new string[] {Environment.NewLine},StringSplitOptions.None));
            stackTrace.RemoveAll(x => x.Contains(_excludeFromStackTrace));
            return string.Join(Environment.NewLine, stackTrace.ToArray());
        }
    }
}

class Program {

    static void TestExc() {
        throw new MyException("Program.TestExc");
    }

    static void foo() {
        TestExc();
    }

    static void Main(params string[] args) {
        try{
            foo();
        } catch (Exception exc){
            Console.WriteLine(exc.StackTrace);
        }
    }

}
Paolo Tedesco
Hmm seems a little bit clumsy but my feeling is now that this might be the only way to do it, so I'll mark it as the answer, thank you.
gordonml
+1  A: 

I am guessing that you want to do this in order to consolidate code that is used to create the exception? In that case, rather than write a ThrowException() function, why not write a GetException() function? Then in Foo, just do throw GetException();

Kenneth Baltrinic
Not entirely true in this specific case, but good idea otherwise, thanks
gordonml