0 votes
by (2.5k points)

If I am catching an exception, there are two ways to throw it again : 

try
{
	throw new Exception('Test');
} catch(Exception ex)
{
	//Should I do this
	//throw;
	
	//Or this?
	throw ex;
}

Do the two different rethrows make a difference?

1 Answer

+1 vote
by (2.5k points)

It actually makes a huge difference!

If you use throw ex :

try
{
	throw new Exception('Test');
} catch(Exception ex)
{
	throw ex;
}

It will throw the exception, but it isn't throwing the original exception (Well, it kind of is kind of isn't). The most important thing here is that when you do this, the line numbers/stack trace changes. Here, it would say that the exception was thrown on line 6. 

But if we just use throw : 

try
{
	throw new Exception('Test');
} catch(Exception ex)
{
	throw;
}

It preserves the original exception as is. So in this example, the stack trace should say that the exception was on line 3, not 6. 

Because of this, it is almost always more useful to use throw; instead of throw ex; when rethrowing an exception in a catch block as you'll get where the original exception actually happened. 

Welcome to .NET Q&A, where you can ask questions and receive answers from other members of the community.
...