This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
You use thewhen
contextual keyword to specify a filter condition in the following contexts:
try-catch
ortry-catch-finally
statement.switch
statement.switch
expression.when
in a catch clauseThewhen
keyword can be used in a catch clause to specify a condition that must be true for the handler for a specific exception to execute. Its syntax is:
catch (ExceptionType [e]) when (expr)
whereexpr is an expression that evaluates to a Boolean value. If it returnstrue
, the exception handler executes; iffalse
, it does not.
The following example uses thewhen
keyword to conditionally execute handlers for anHttpRequestException depending on the text of the exception message.
using System;using System.Net.Http;using System.Threading.Tasks;class Program{ static void Main() { Console.WriteLine(MakeRequest().Result); } public static async Task<string> MakeRequest() { var client = new HttpClient(); var streamTask = client.GetStringAsync("https://localHost:10000"); try { var responseText = await streamTask; return responseText; } catch (HttpRequestException e) when (e.Message.Contains("301")) { return "Site Moved"; } catch (HttpRequestException e) when (e.Message.Contains("404")) { return "Page Not Found"; } catch (HttpRequestException e) { return e.Message; } }}
Was this page helpful?
Was this page helpful?