Why does the high part of the stack (in Exception.StackTrace) gets truncated? Let's see a simple example:
public void ExternalMethod()
{
InternalMethod();
}
public void InternalMethod()
{
try
{
throw new Exception();
}
catch(Exception ex)
{
// ex.StackTrace here doesn't contain ExternalMethod()!
}
}
It seems like this is "by design". But what are the reasons for such a strange design? It only makes debugging more complex, because in log messages I can't understand who called InternalMethod() and often this information is very necessary.
As for solutions (for those who don't know), there are 2 general solutions as I understand:
1) We can log static Environment.StackTrace property, which contains the whole stack (for example, starting at the hiest level (message queue) and ending at the deepest method in which exception occurs).
2) We have to catch and log exceptions on highest levels. When we need to catch exceptions on lower levels to do something, we need to rethrow (with "throw" statement in C#) it further up.
But the question is about reasons of such design.
Ok, now I see what your getting at... Sorry for my confusion on the inlining thing.
The 'stack' in a caught exception is only a delta from the currently executing catch block to where the exception was thrown. Conceptually this behavior is correct in that the Exception.StackTrack tells you where the exception occurred within the context of this try/catch block. This allows exception stacks to be forwarded across 'virtual' calls and still maintain accuracy. One classic example of this being done is .Net Remoting exceptions.
Thus if you want a complete stack report in the catch block you would add the current stack to the exception's stack as in the example below. The only problem is this can be more expensive.
As csharptest said this is by design. The StackTrace stops at the try block. Further more there is no hook in the framework that is called when an exception is thrown.
So the best you can do is something along these lines, it its an absolute requirement to get full stack traces (store a full trace on exceptions creation):
Outputs:
It is not possible to inject this behaviour into the existing System defined exceptions, but .Net has a rich infrastructure for wrapping exceptions and rethrowing so it should not be a huge deal.
I know that in a catch block if you do
throw ex;
it truncates the stack trace at that point. It's possible that it's "by design" for throw since justthrow;
doesn't truncate the stack in a catch. Same may be going on here since you're throwing a new exception.What happens if you cause an actual exception (i.e.
int i = 100/0;
)? Is the stack trace still truncated?This is often caused by the compiler optimizations.
You can decorate methods you do not want to inline by using the following attribute: