when C# with Example



when C# with Example

The when is a keyword added in C# 6, and it is used for exception filtering. 
Before the introduction of the when keyword, you could have had one catch clause for each type of exception; with 
the addition of the keyword, a more fine-grained control is now possible. 
A when expression is attached to a catch branch, and only if the when condition is true, the catch clause will be 
executed. It is possible to have several catch clauses with the same exception class types, and different when 
conditions. 
private void CatchException(Action action) 
{ 
try 
{ 
action.Invoke(); 
} 
// exception filter 
catch (Exception ex) when (ex.Message.Contains("when")) 
{ 
Console.WriteLine("Caught an exception with when"); 
} 
catch (Exception ex) 
{ 
Console.WriteLine("Caught an exception without when"); 
} 
} 
 

private void Method1() { throw new Exception("message for exception with when"); } 
private void Method2() { throw new Exception("message for general exception"); } 
CatchException(Method1); 
CatchException(Method2); 

0 Comment's

Comment Form

Submit Comment