-
Notifications
You must be signed in to change notification settings - Fork 4.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
C# exceptions and rethrow #7106
Comments
Well,
I'm not aware of a way to avoid this. Besides, this is not specific to any particular version of C# and .NET, to the best of my knowledge all behave like this since day 1. Personally I avoid this kind of code whenever possible. Not necessarily because line number information is lost because I find it weird to throw an exception and then catch and rethrow it just below. But of course, it's not always possible to avoid this kind of code in a reasonable fashion. |
Does |
Hmm, looks like it could help, it doesn't produce the exact same stack trace that a "proper" rethrow would produce but at least it contains both locations: static void g()
{
try
{
throw new Exception("A"); // line 26
}
catch (Exception e)
{
e.ToString();
ExceptionDispatchInfo.Capture(e).Throw(); // line 31
}
} generates
|
I think I finally found the issue documented very clearly in MSDN The common language runtime (CLR) updates the stack trace whenever an exception is thrown in application code (by using the throw keyword). If the exception was rethrown in a method that is different than the method where it was originally thrown, the stack trace contains both the location in the method where the exception was originally thrown, and the location in the method where the exception was rethrown. If the exception is thrown, and later rethrown, in the same method, the stack trace only contains the location where the exception was rethrown and does not include the location where the exception was originally thrown. I just wish it was part of the throw; msdn documentation so that it is easier to co-relate. |
@saxenark Can this be closed? |
Yes, please close this. Thanks. |
In the program below, I expected to have the line "throw new Exception("A")" also reported when I dump the exception object in Main. Unfortunately, this information is being lost even though I am doing a rethrow using throw;. Two questions:
a) Why is this behavior when throw; is supposed to preserve call stack?
b) What is the recommended way to handle this across different versions of C# and .NET?
The text was updated successfully, but these errors were encountered: