Amy Amy - 1 month ago 7
C# Question

How can I tell the compiler to ignore a method in stack traces?

Are there any attributes I can apply to boilerplate methods so that such methods do not appear in stack traces? I've got a lot of them and in some cases they are several levels deep. It's just cluttering things.

Example code:

class Program
{
public static void ThrowMe()
{
throw new NotImplementedException();
}

public static void HideMe()
{
ThrowMe();
}
static void Main(string[] args)
{
try
{
HideMe();
}
catch (Exception e)
{

}
}
}


This throws this stack trace:


at Spork.Program.ThrowMe() in C:\Projects\XXX\Testing Sandbox\ConsoleTesting\Program.cs:line 58

at Spork.Program.HideMe() in C:\Projects\XXX\Testing Sandbox\ConsoleTesting\Program.cs:line 64

at Spork.Program.Main(String[] args) in C:\Projects\XXX\Testing Sandbox\ConsoleTesting\Program.cs:line 70

Answer

Put Console.WriteLine(e) in the catch block. Switch to the release build and press Ctrl+F5. You'll see this:

System.NotImplementedException: The method or operation is not implemented.
   at ConsoleApplication1.Program.ThrowMe() in C:\Users\hpassant\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs:line 9
   at ConsoleApplication1.Program.Main(String[] args) in C:\Users\hpassant\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs:line 17 

Note that the HideMe() method is not visible in the stack trace. Mission accomplished.

The method call was not shown in the trace because the JIT optimizer inlined the method: this is the only way to hide methods in the stack trace.

It is not something you can control well, the method has to be 'small' and not throw any exception itself. This is otherwise normally considered a problem, not a feature. Hard to figure out how to code got from A to B.