Friday, September 5, 2008

Event Driven Error Handling

I have been reading a new titled "Design Patterns in C#". It is a great book, tons of information and it is quite understandable. While reading through the observer pattern it struck me. Why do we need to use so may try/catch statements in our code when we could fire off the exceptions from an event handler.

So I wrote up some quick code to test it out.

public delegate void TestErrorHandler(string message);

public class TestClass
{
public event TestErrorHandler test;

public void TriggerHandler(object blah)
{
if (blah == null)
{
test("Null argument in TriggerHandler");
}
}
}

static void Main(string[] args)
{
TestClass MyTest = new TestClass();
MyTest.test += new TestErrorHandler(OhCrap);
MyTest.TriggerHandler(null);
}

public static void OhCrap(string e)
{
Console.WriteLine(String.Format("Oh CRAP! {0}", e));
Console.Read();
}

I can see some pitfalls to this solution like:
1. You fire off the same Exception Event from multiple methods, i.e. ArgumentNullException.
2. How do you tell what observing method called the method that threw the Exception Event? For instance what if you had a private property that had the same methods being called multiple times?
3. What about if I call the same method multiple times from the same piece of code. a for loop for instance?

These are definitely challenging issues to solve but I feel it may be possible. I already have some ideas but right now don't have the time to fully test these out. If it is possible then it could take decoupling code to a whole new level.

No comments: