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?
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.
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.
To keep the original stack trace information with the exception, use the throw statement without specifying the exception.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With