Exercises for SASP 2008, week 2

This week there is one exercise, which is to build an library that implement recoverable exeptions in C#. To build such a library in full is way more complicated than what one can do in a hand-in, but we shall get far enough to get an idea of how it could be done.

We will take outset in the following code:

namespace ResumeableExceptions {
    class Program {
        static void Main(string[] args) {
            int x=8;
            Resumable.Call(
                delegate() { x = Uups(true); },
                delegate() { Resumable.Recover(10); });
            Console.Out.WriteLine("X is: " + x);
        }

        static int Uups(bool fail) {
            if (fail)
                return Resumable.Throw();
            return 17;
        }
    }

    delegate void AnonymousAction();

    class Resumable {
        public static void Call(AnonymousAction action, AnonymousAction handle) {
        }
        public static void Recover(int returnValue) {
        }
        public static void Fail() {
        }

        public static int Throw() {
        }
    }
}

The exercise is to fill out the missing parts of the Resumable class.
The Call method takes two delegates - anonymous lambda expressions - as parameter. The first parameter is the body to be executed - serving the same role as try-part in a try-catch construct. The second is the handler - the catch-part if you will. We have for simplicity ignored different kinds of exceptions.
In the Main method, the action is to assign x the value returned by the Uups method. However, the Uups method might fail.

In the case above, it does. In Uups, a ResumableException is indeed thrown. When a ResumableException is thrown the handler passed to Call must be executed. If the handler executes the Recover method, the value passed as argument to Recover is used as return value of the Throw call, and execution continues after Throw as if no exeption had occured. If the handler does not execute a Recover call, handler is fully executed, and the entire Call statement is abandoned. The handler can explicitly execute the Fail method causing the handler to finish immediately.

To solve this exercise, it is necessary to use the standard exception handling mechanisms of C# internally in class Resumable. 

The entire solution can be kept in one file, so just hand in that one file - as an attachment - to kasper@itu.dk.