Our program is great only when we handle exceptions appropriately.
We all know that we can catch different type of Exceptions in C# with try/catch, but we always forget to be a bit more specific.
There are several interesting example in official docs, so I pick up one to explain how this works.
See this document for more detail.
Sample code
Let's create sample code as console app.
using System;
namespace ExceptionFilter
{
class Program
{
static void Main(string[] args)
{
int[] array = { 1, 2, 3 };
int index = -1;
try
{
int result = array[index];
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("IndexOutOfRangeException", e);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine("something went wrong!");
}
}
}
}
When I run the program, I see IndexOutOfRangeException as expected.
However, what if I want distinguish when user put negative value and when user put larger size than the array length? Then I can use when exception filter like below.
using System;
namespace ExceptionFilter
{
class Program
{
static void Main(string[] args)
{
int[] array = { 1, 2, 3 };
int index = -1;
try
{
int result = array[index];
}
catch (IndexOutOfRangeException e) when (index < 0)
{
Console.WriteLine("Parameter index cannot be negative.", e);
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine(e.Message);
Console.WriteLine("Parameter index cannot be greater than the array size.");
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine("something went wrong!");
}
}
}
}
That's it! It may sound stupid, but in real case life, we had to do if/else statement inside catch several years ago :D
Top comments (0)