Categories
.NET Core

Throw or throw ex in C#?

One common question that comes up when working with exceptions in C#, is whether or not you should re-throw an existing exception by specifying the exception, or just using the throw keyword where an error occurs.

In most cases, it’s best to rethrow the existing exception, such as below:

try {	var networkResponse = await someNetworkService.GetAllPosts();}catch (Exception ex){	Log.Warning("An exception occurred", ex);	//Now lets rethrow this same exception	throw;}

By doing so, you ensure that the original stack trace for the exception is maintained. If you were to instead do something like this:

try {	var networkResponse = await someNetworkService.GetAllPosts();}catch (Exception ex){	Log.Warning("An exception occurred", ex);	//Now lets throw ex again	throw ex;}

You’ll now see that the exception stack trace only goes as far back as this line of code – not to the raw source of the exception.

In short, that’s why its normally better to just throw again, instead of specifying the exception when re-throwing.

Leave a Reply

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