Tuesday 18 October 2011

Throw-catch programming

Sometimes people say it's not good to encode your programming logic in exception terms. I wonder why not. We should just love and embrace exceptions.

class CounterException : Exception
{
public readonly int Index;
public readonly int Max;
public CounterException(int index, int max)
{
this.Index = index;
this.Max = max;
}
public Exception Next
{
get
{
if (Index == Max)
{
return new FinishedCountingException(Max);
}
else
{
Console.WriteLine("Count = " + Index);
return new CounterException(Index + 1, Max);
}
}
}
}
class FinishedCountingException : Exception
{
public readonly int Bound;
public FinishedCountingException(int b)
{
Bound = b;
}
}
class Program
{
static void Main(string[] args)
{
Exception e = new CounterException(0, 10);
mytry:
try
{
throw e;
}
catch (CounterException ex)
{
e = ex.Next;
goto mytry;
}
catch (FinishedCountingException ex)
{
Console.WriteLine("Finished counting to " + ex.Bound);
}
Console.ReadKey();
}
}