Bhavya

Code -> Break -> Fix -> Blog

C# 6.0 : Exceptions Filters

1 Comment

Visual Basic & F# allows catch blocks to filter exceptions before actually catching them.

With C# 6.0, a C# developer can do the same.

try
 {
 // Create a web request for an invalid site. 
 var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("invalid site");

// Get the associated response for the above request.
 var myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
 myHttpWebResponse.Close();
 }
 catch (WebException webEx) if(webEx.Status==WebExceptionStatus.ProtocolError)
 {
 WriteLine("Protocol Error -> Status Description : {0}", 
 ((HttpWebResponse)webEx.Response).StatusDescription);
 }

In the above code, the catch block will only be executed if the Status is ProtocolError.

Also, with C# 6.0, the developer can use await keyword in catch and finally block.

 catch (WebException webEx) if(webEx.Status==WebExceptionStatus.ProtocolError)
 {
 await LogAsync(webEx.Message);
 }

Let me know your thoughts.

~BS

Twitter Logo

Advertisements

One thought on “C# 6.0 : Exceptions Filters

  1. Pingback: New Features of C# 6.0 | Bhavya

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s