Skip to content

The throw keyword shows the wrong thrown exception line #9518

@jkotas

Description

@jkotas

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementProduct code improvement that does NOT require public API changes/additionshelp wanted[up-for-grabs] Good issue for external contributors

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions