skip to Main Content

I work with code which looks similar to:

try {
    f1();
    f2();
    f3();
}
catch(Exception) {
    //...
}

If in Visual Studio I set a breakpoint within the catch block, is there a way for me to find out which function in the try block threw the exception?

Removing the try block to see when the program crashes is not a viable option for me.

The type of the exception does not allow to make a guess easily.

2

Answers


  1. Check the stack trace in the exception object.

    Login or Signup to reply.
  2. You can use the StackTrace proprty of the Exception:

    A string that describes the immediate frames of the call stack. If no
    stack trace is available (such as prior to stack unwinding from a
    throw statement), the value is null.

    This string will give you the stack of function calls leading to the exception, including the line number for each call. If you have multiple calls to the function throwing the exception, you can find out exactly which call triggered it from the line number.

    This is demonstrated in the test below:

    using System;
    
    namespace Test
    {
        class Program
        {
            static void f1() {}
    
            static void f2() {}
    
            static void f3(int n) { if (n == 2) throw new Exception(); }  // line 11
    
            static void Main(string[] args)
            {
                try
                {
                    f1();
                    f2();
                    f3(1);
                    f3(2);   // line 20
                    f3(3);
                }
                catch (Exception e)
                {
                    var st = e.StackTrace;
                    Console.WriteLine(st);
                }
            }
        }
    }
    

    Output:

       at Test.Program.f3(Int32 n) in C:<...>Program.cs:line 11
       at Test.Program.Main(String[] args) in C:<...>Program.cs:line 20
    

    As you can see, the call to f3 was originated in Main, line 20 (the call with n==2).

    Note:
    The output above was acquired from a Debug build. In Release build some information might be missing or inaccurate (due to optimizations etc.).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search