Home » Tutorials » C# » Difference between Throw and Throw ex in C#

Difference between Throw and Throw ex in C#

Use of Yield in C#
Use of Private Constructor in C# with an example

Difference between Throw and Throw ex in C#

Hey folks, till day you have read Difference between Var and Dynamic in c#,Difference Between WCF and WebAPIDifference between String and string in C#Difference between Nullable<> and ?,Difference between Hashtable and Dictionary,Insert data into Database table using SQLBulkCopy class in C#Ping in C# , Call method after specific time interval C#Insert Retrieve images from Database in asp.net LINQ TO SQLCompare two objects in C# and datakey from GridView RowCommand. Today we will discuss regarding Difference between Throw and Throw ex in C# with an example.

As you all know throw and throw ex are used in catch part of the thy..catch block. Let’s try to understand one by one first and then try to understand what is the exact difference between them.

Understanding of throw:

Here we have two methods named with Method1() and Method2(). From Method1() method2() has been called and here Method2 is throwing custom exception “only use throw in catch block”. As we have used Throw only in Method1 and Method2, it will print full trace of exception as shown below image.

Throw-In-C#

Throw-In-C#

Understanding of throw ex:

Here we have two methods named with Method1() and Method2(). From Method1() method2() has been called and here Method2 is throwing custom exception “only use throw in catch block”. As we have used Throw only in Method1 and Method2, it will not print full trace of exception as we have got in throw as shown below image. We could get only last exception details. So StackTrace has been overridden by Method2().

Throw-ex-in-C#

Throw-ex-in-C#

Conclusion with difference:

throw : If we use “throw” statement, it preserve original error stack information. In exception handling “throw” with empty parameter is also called re-throwing the last exception.

throw ex : If we use “throw ex” statement, stack trace of exception will be replaced with a stack trace starting at the re-throw point. It is used to intentionally hide stack trace information.

About

Hello friends, My self Dhruv Sheth, I have more than 6 years of Industrial experience as a Software Developer. In my career I got chance to work with asp.net, c#,Web API, JavaScript, JQuery, WPF, WCF , Windows Application, PostScript, vb.net, GhostScript etc. So I have decided to share my knowledge with everyone and finally I have come up with TechnoThirsty.

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*

Time limit is exhausted. Please reload CAPTCHA.




DISCLAIMER:
The content is copyrighted to technothirsty.com and may not be reproduced on other websites without permission from the owner.You may contact us using the information below.