throw vs throw ex in c#

we all have been writing c# code and everyone of us, surely do make use of try catch blocks. With try catch blocks we make use of another statement quite regularly i.e. throw.

In below table I tried summarize the difference between throw and throw ex:

throw throw ex
try{

// do some work here

}   catch (Exception ex)

{

// do some action

throw;

}

try{

// do some work here

}  catch (Exception ex)

{

// do some action

throw ex;

}

Stack information is preserved with Exception Stack information in NOT preserved with Exception
This is kind of “rethrow” of Exception This is kind of “Breaking the Stack” handling of Exception

If you are really looking for exception trace for analysis purpose at the exception handler method always use throw and NOT throw ex.

Of Course you can throw a new exception type through both throw and throw ex:

throw new MyException(“operation failed!”);

OR

throw new MyException(“operation failed!”, ex);

Trace will be preserved in first code syntax and not in second.

Keep doing a healthy code!!

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

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