I have a class with number of methods and want to have one exception handler for them all. There are so many of these methods and they have different parameters, that it would b
I can't figure out any reason why you may benefit from handling all the exceptions in a class using a single method (can you elaborate? I'm curious...)
Anyway, you can use AOP (Aspect Oriented Programming) techniques to inject (statically or at runtime) exception handling code around the methods of your class.
There's a good assembly post-processing library called PostSharp that you can configure using attributes on the methods in your class:
You may define an aspect like this (from PostSharp website):
public class ExceptionDialogAttribute : OnExceptionAspect
{
public override void OnException(MethodExecutionEventArgs eventArgs)
{
string message = eventArgs.Exception.Message;
MessageBox.Show(message, "Exception");
eventArgs.FlowBehavior = FlowBehavior.Continue;
}
}
And then you'll apply the attribute to the methods you want to watch for exceptions, like this:
public class YourClass {
// ...
[ExceptionDialog]
public string DoSomething(int param) {
// ...
}
}
You can also apply the attribute to the whole class, like this:
[ExceptionDialog]
public class YourClass {
// ...
public string DoSomething(int param) {
// ...
}
public string DoSomethingElse(int param) {
// ...
}
}
This will apply the advice (the exception handling code) to every method in the class.