Handling exceptions is a fact of life in C# and sometimes you want to catch an exception but only if certain conditions are true.
Prior to this feature you were forced to throw the exception again and in doing so cause the debugger to break on your throw line rather than on the original target.
Code
C#
async Task SaveUrl(string path, Uri uri)
{
var response = await client.GetAsync(uri);
try
{
response.EnsureSuccessStatusCode();
File.WriteAllText(path, await response.Content.ReadAsStringAsync());
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.Redirect)
{
await SaveUrl(path, response.Headers.Location);
}
}
C#
async Task SaveUrl(string path, Uri uri)
{
var response = await client.GetAsync(uri);
try
{
response.EnsureSuccessStatusCode();
File.WriteAllText(path, await response.Content.ReadAsStringAsync());
}
catch (HttpRequestException ex)
{
if (ex.StatusCode == HttpStatusCode.Redirect)
await SaveUrl(path, response.Headers.Location);
else
throw;
}
}
Notes
- Adding an exception filter means the exception was never caught at all if the conditions do not match