What are the differences between "throw"?

Visit Website View Our Posts

What are the differences between "throw", "throw ex" and "throw new Exception()"?

“throw” is key word used in C# when generating an error condition that can be handled by a try...catch...finally block.
The throw statement can be used with or without an argument. When it is used without an argument, the throw statement must be contained within a catch block.

 

  1. Using throw only

Source code:

Error message:

2. Using throw ex

Source code:

Error message:

3. Using throw new Exception()

Source code:

Error message:

To conclude, throw can preserve the original stack trace and show you where the error originally occurs. In this example, the stack trace shows the error occurs at line 30 from the Divide() method while the stack trace only shows that the error is originated at line 24 from the Calculate() method when throw ex is used. And if you want to add some additional message into the error message, throw new Exception() is a handy choice. You can also add ex as an InnerException shown in the example to preserve the stack trace.

 

This article was written by Joe Qian, Consultant for Tridea Partners. Tridea is a leading Microsoft Dynamics provider.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Show Buttons
Hide Buttons