runtime: The throw keyword shows the wrong thrown exception line

From @NicolasDorier on August 22, 2017 14:56

Using .NETCore2.0, Win10, it seems the throw keywor

Using the throw keyword loose all the initial stacktrace information. You can workaround with ExceptionDispatchInfo.Capture(ex).Throw();, but this seems like a bug to me.

using System;

namespace ConsoleApp3
{
	class Program
	{
		static void Main(string[] args)
		{
			try
			{
				DoStuff();
			}
			catch(Exception ex)
			{
				Console.WriteLine(ex.StackTrace);
			}
			
		}

		private static void DoStuff()
		{
			try
			{
				throw new Exception("Boom!");
			}
			catch(Exception ex)
			{
				throw;
			}
		}
	}
}

Actual output: (Exception line 28)

   at ConsoleApp3.Program.DoStuff() in c:\users\nicolasdorier\documents\visual studio 2017\Projects\ConsoleApp3\ConsoleApp3\Program.cs:line 28
   at ConsoleApp3.Program.Main(String[] args) in c:\users\nicolasdorier\documents\visual studio 2017\Projects\ConsoleApp3\ConsoleApp3\Program.cs:line 11

Expected output: (Exception line 24)

   at ConsoleApp3.Program.DoStuff() in c:\users\nicolasdorier\documents\visual studio 2017\Projects\ConsoleApp3\ConsoleApp3\Program.cs:line 24
   at ConsoleApp3.Program.Main(String[] args) in c:\users\nicolasdorier\documents\visual studio 2017\Projects\ConsoleApp3\ConsoleApp3\Program.cs:line 11

Workaround using ExceptionDispatchInfo.Capture(ex).Throw();:

using System;
using System.Runtime.ExceptionServices;

namespace ConsoleApp3
{
	class Program
	{
		static void Main(string[] args)
		{
			try
			{
				DoStuff();
			}
			catch(Exception ex)
			{
				Console.WriteLine(ex.StackTrace);
			}
			
		}

		private static void DoStuff()
		{
			try
			{
				throw new Exception("Boom!");
			}
			catch(Exception ex)
			{
				ExceptionDispatchInfo.Capture(ex).Throw();
				throw;
			}
		}
	}
}

Copied from original issue: dotnet/corefx#23470

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 2
  • Comments: 16 (15 by maintainers)

Commits related to this issue

Most upvoted comments

From @danmosemsft on December 6, 2017 23:35

I don’t think anyone wants the line number on the throw;, it is a bug, we would accept a fix for it, I think it is clearest to reopen this. The fix would be in CoreCLR.

I can’t believe this is really happening! 🎉

@fujiy yes this will be in .NET Core 2.1, albeit not in the Preview 1 as that branched already. I don’t think CoreFX ingested it yet, but in a few days, please try it in master.

For .NET Framework - it is marked netfx-port-consider for our next pass through potential ports. I can’t give a timeframe for that.

@danmosemsft, will this change be included in .NET Core 2.1? What about be ported to .NET Framework?

Thx!