Diff between throw and throw ex

When you rethrow exception use throw rather than throw ex which destroys stack trace.

Consider small example :-


try
{
testMethod();
}
catch(Exception ex) {

}

private static void testMethod()
{
try
{
string str = "";

str.Substring(2);
}
catch (Exception ex1)
{
throw ex1;
}

}

In above example we are throwing exception we caught here ex1 to parent function. in this case we will
catch this exception in parent unction catch but we will lost with stack trace.

So always try to use throw instead of throw ex1 in your child functions.

If we ran Above example we will get stack trace in parent function as below
at CSLA_PracticeSolution.Program.testMethod() in D:\Test\CSLA-PracticeSolution\CSLA-PracticeSolution\Program.cs:line 79
at CSLA_PracticeSolution.Program.Main(String[] args) in D:\Test\CSLA-PracticeSolution\CSLA-PracticeSolution\Program.cs:line 16

But if you just use throw instead of throw ex1 in child function you will get

at System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy)
at System.String.Substring(Int32 startIndex)
at CSLA_PracticeSolution.Program.testMethod() in D:\Test\CSLA-PracticeSolution\CSLA-PracticeSolution\Program.cs:line 79
at CSLA_PracticeSolution.Program.Main(String[] args) in D:\Test\CSLA-PracticeSolution\CSLA-PracticeSolution\Program.cs:line 16

Thanks ..


					
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s