throw e;were e is the exception we caught.
Why don't we do the same in C# and see what will happen. Below is a sample code that illustrates such situation:
class ProgramNow lets execute it and examine the stack trace:
{
void m1() { m2(); }
void m2() { m3(); }
void m3() { m4(); }
void m4()
{
throw new Exception("A sample exception.");
}
static void Main(string[] args)
{
try
{
new Program().m1();
}
catch(Exception e)
{
throw e;
}
}
}
System.Exception was unhandledWhat did happen here? We somehow lost the whole stack trace. Now it looks like the exception was created within the Main method – in a real life scenario that may cause many problems when troubleshooting.
Message=A sample exception.
Source=LearningCsharp
StackTrace:
at ConsoleApplication1.Program.Main(String[] args) in C:\Path\Program.cs:line 220
…
How to do it correctly in C# and preserve the whole stack trace? Here is the answer:
class ProgramYes! Simple
{
void m1() { m2(); }
void m2() { m3(); }
void m3() { m4(); }
void m4()
{
throw new Exception("A sample exception.");
}
static void Main(string[] args)
{
try
{
new Program().m1();
}
catch(Exception e)
{
throw;
}
}
}
throw;solves the issue. Now our stack trace will look as follows:
System.Exception was unhandledLooks much better – we can see which method thrown the exception and thus find the source of the issue.
Message=A sample exception.
Source=LearningCsharp
StackTrace:
at ConsoleApplication1.Program.m4() in C:\Path\Program.cs:line 210
at ConsoleApplication1.Program.m3() in C:\Path\Program.cs:line 207
at ConsoleApplication1.Program.m2() in C:\Path\Program.cs:line 206
at ConsoleApplication1.Program.m1() in C:\Path\Program.cs:line 205
at ConsoleApplication1.Program.Main(String[] args) in C:\Path\Program.cs:line 220
...
So Java developers – bear that difference in mind and avoid confusion when analyzing a half empty stack trace! :)