The first code snippet is a trivial code, a repository class trying to get the user type for the given user. The method catches the exception, log it and re-throw it.

The second code snippet is invoking the repository method. Calling the DB method is wrapped inside a try-catch block. In the catch block its printing the exception stack trace.

StackTrace with 'throw' statement

Now we have set the stage to understand the practical difference between 'throw' and 'throw ex'. Let's run the code AS IS, i.e., by using the throw statement inside the repository method catch block. Let's break the SQL Connection before running the code, so that it will lead to an exception. Look at the below stacks trace, it shows the stack trace of the original exception as well.

StackTrace with 'throw ex' statement

Now modify the code in the repository method catch block to use the 'throw ex' statement and run the app. This time you will see the below Exception StackTrace. Note, it doesn't include the original exception's stack trace.

Where to use 'throw ex' over 'throw'

When you think exception stacks trace give away confidential information, then use throw ex. Especially when you are writing public repository methods and also when you throwing exceptions from service layer.

You don't want to give away the information about the database you are using and the libraries you are using to consumers of your services. Because hackers are around. By looking at the Stack Trace, bad guys will make out certain things, which you may not be comfortable in giving away.

Hope you understood the difference between throw and throw ex and also when to use what over the other. Feel free to comment on the post.