Click here to Skip to main content
14,574,641 members

.NET: Exception Stack Trace Has No Frames Above the Catch Point

Rate this:
4.00 (1 vote)
Please Sign up or sign in to vote.
4.00 (1 vote)
25 Oct 2010Apache
.NET - Exception stack trace has no frames above the catch point

I never thought about it, but it turns out that exception’s stack trace does not contain the full stack. Instead, it contains only frames between the point where the exception was thrown and the point it is caught. This is bad if exception is caught close to the point of throwing and logged:

using System;

namespace ExceptionTrace
{
    class Program
    {
        void f1()
        {
            f2();
            f3();
        }
 
        void f2() { f4(); }
        void f3() { f4(); }
 
        void f4()
        {
            try { throw new Exception("Boo!"); }
            catch (Exception ex)
            {
                Console.WriteLine("Problem: " + ex); // stack trace contains only f4()
            }
        }
 
        static void Main(string[] args)
        {
            new Program().f1();
        }
    }
}

This prints:

Problem: System.Exception: Boo!
   at ExceptionTrace.Program.f4() in C:\Ivan\dev\exp\ExceptionTrace\Program.cs:line 18
Problem: System.Exception: Boo!
   at ExceptionTrace.Program.f4() in C:\Ivan\dev\exp\ExceptionTrace\Program.cs:line 18

Note that both stack traces are exactly identical and contain only one frame. The message does not say whether f4() was called from f2() or from f3(). This information can be obtained by calling new StackTrace() inside the catch, which returns the full stack, but this stack trace is not part of the exception.

If we rethrow the exception and let it travel up the call chain, its StackTrace will automatically grow to reflect additional frames, but it will never include the frames above the catching block.

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0

Share

About the Author

Ivan Krivyakov
Technical Lead Thomson Reuters
United States United States
Ivan is a hands-on software architect/technical lead working for Thomson Reuters in the New York City area. At present I am mostly building complex multi-threaded WPF application for the financial sector, but I am also interested in cloud computing, web development, mobile development, etc.

Please visit my web site: www.ikriv.com.

Comments and Discussions

 
-- There are no messages in this forum --
Technical Blog
Posted 25 Oct 2010

Tagged as

Stats

13.4K views
2 bookmarked