.NET Tips and Tricks

Blog archive

What's New in C# 6.0: Selecting Exceptions in a Try...Catch Block

Visual Basic developers can put conditions on a catch block in a try...catch to control which catch block is executed when an error occurs.

With C# 6.0, C# developers can now do the same by adding a if test to the catch statement. This example checks the error message associated with the Exception object's InnerException to decide which catch block to execute:

try
{
   ...code...
 }
 catch (Exception ex) if (ex.InnerException.Message == "Parameter Error")
 {
   ...error handling code...
 }
 catch (Exception ex) if (ex.InnerException.Message == "Math Error")
 {
   ...error handling code...

How VBish is that?

Posted by Peter Vogel on 04/23/2015


comments powered by Disqus

Featured

Subscribe on YouTube