Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find where rethrown exception was originally thrown using Visual Studio C# debugger?

The usual advice when rethrowing an exception is to use a throw; statement so the original stack trace is preserved. (Example)

However, when I try this simple example, the Visual Studio debugger does not show the original stack trace.

namespace ExceptionTest
{
    class Program
    {
        static void ThrowException()
        {
            throw new System.Exception();  // The line that I WANT the debugger to show.
        }

        static void Main(string[] args)
        {
            try
            {
                ThrowException();
            }
            catch (System.Exception)
            {
                System.Console.WriteLine("An exception was thrown.");

                throw;  // The line that the debugger ACTUALLY shows.
            }
        }
    }
}

How can I use the debugger to find the original source of the exception?

like image 352
Jon-Eric Avatar asked Feb 09 '12 20:02

Jon-Eric


People also ask

How do I break an exception in Visual Studio?

Tell the debugger to break when an exception is thrownIn the Exception Settings window (Debug > Windows > Exception Settings), expand the node for a category of exceptions, such as Common Language Runtime Exceptions. Then select the check box for a specific exception within that category, such as System.

How do you Rethrow in C#?

An exception caught by one catch can be rethrown so that it can be caught by an outer catch. To rethrow an exception, you simply specify throw, without specifying an expression.

What statement should you use to Rethrow a caught exception named ex without losing the stack trace?

To keep the original stack trace information with the exception, use the throw statement without specifying the exception.


1 Answers

Your best option is to ask Visual Studio to break on the original exception rather than navigate back to it from the stack trace. To do this:

1) Click on the 'Debug' menu item 2) Click 'Exceptions...' 3) Select 'Common Language Runtime Exceptions' - 'Thrown'

With this approach you may get more than you really wanted if there are many exceptions being thrown. You can filter which exceptions it breaks on by expanding the tree list.

See image:

enter image description here

like image 173
Rob Smyth Avatar answered Sep 29 '22 14:09

Rob Smyth