Click here to Skip to main content
13,801,506 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

11.5K views
2 bookmarked
Posted 25 Oct 2010
Licenced Apache

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

, 25 Oct 2010
Rate this:
Please Sign up or sign in to vote.
.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.

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.181215.1 | Last Updated 25 Oct 2010
Article Copyright 2010 by Ivan Krivyakov
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid