Reputation: 631
I have tried several suggestions on how to keep the correct line number in the stack trace when throwing an exception. The most common being just catch and throw, but that doesn't work. Here are a few I've tried:
private void button1_Click(object sender, EventArgs e)
{
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void test()
{
try
{
int a = 1;
int b = 0;
int x = 0;
x = a / b;
}
catch
{
throw;
}
}
And a few variations on the catch block.
catch (Exception)
{
throw;
}
catch (Exception e)
{
throw;
}
catch (Exception e)
{
throw e;
}
All of these report error on the throw line and the message box line - never on the line that divides by 0. If I break inside the test() function, it does show the right line #, but after being thrown does not. The only way that has worked is to not have any try/catch in the test() function. But of course I want to be able to catch errors and re-throw them and keep the stack trace correct. So how is this done?
Thank you.
Upvotes: 6
Views: 1215
Reputation: 3792
You want ExceptionDispatchInfo.Capture(ex).Throw();
.
This might be a duplicate of this other question.
Upvotes: 5
Reputation: 903
The simplest way is to simply remove the try catch in test. If that is not an option, as mentioned in the comment above, you can throw a new exception, passing in the old exception and look for the inner exception for actual stack trace info.
private void button1_Click(object sender, EventArgs e)
{
try
{
test();
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException.ToString());
}
}
public void test()
{
try
{
int a = 1;
int b = 0;
int x = 0;
x = a / b;
}
catch (Exception e)
{
throw new Exception("inner exception", e);
}
}
Upvotes: 0
Reputation: 13765
In release time you will not have the line number as the number of line is retrieved from the *.pdb
file which contains all symbols of compilation.
So if you are planning to get the exact line number in release / production you have to copy the pdb file
Upvotes: 1