One of my most favorite features of C# 6.0 is the Exception Filter. This allows an exception to be caught in the CATCH block, only a specified condition is met when the exception is thrown. Prior to C# 6.0, we did not have any mechanism to filter the exception in the catch block. We used the if-else statement in the same catch block to bring some sort of filter. To understand it better, let us consider the listing below:
Home » .Net » 4. New Features in C# 6.0 - Exception Filter
4. New Features in C# 6.0 - Exception Filter
One of my most favorite features of C# 6.0 is the Exception Filter. This allows an exception to be caught in the CATCH block, only a specified condition is met when the exception is thrown. Prior to C# 6.0, we did not have any mechanism to filter the exception in the catch block. We used the if-else statement in the same catch block to bring some sort of filter. To understand it better, let us consider the listing below:
static void Main(string[] args)
{
int number = 28;
try
{
int rem = number / 0;
WriteLine(rem);
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
}
ReadKey(true);
}
The major problem in the above snippet is that we cannot apply a filter in the catch block. In C# 6.0, the exception filter can be applied as shown in the listing below:
static void Main(string[] args)
{
int number = 24;
try
{
int rem = number % 0;
WriteLine(rem);
}
catch (DivideByZeroException ex) when (ex.Message.Contains("ck"))
{
WriteLine(ex.Message);
}
catch (DivideByZeroException ex) when (ex.Source == "ConsoleApplication1")
{
WriteLine(ex.Source);
}
ReadKey(true);
}
In C#6.0 using “when”, we can filter the exception. In the above snippet in particular, the catch statement will be thrown only when the condition in the when statement is true. The filtering exception could be very useful here.
0 comments :
Post a Comment