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.
- Using throw only
2. Using throw ex
3. Using throw new Exception()
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