I want to know if is there any way to pass a function to another function to handle its try/catch. I am working on an existing codebase that does not have any Exception handling.
-
I think this questions answer lies along the lines of [Aspect Oriented Programming](http://en.wikipedia.org/wiki/Aspect-oriented_programming). Have a look a [PostSharp](http://www.sharpcrafters.com/). – Ahmad Nov 23 '11 at 04:39
4 Answers
NOTE: This answer addresses the text of the question rather than the title, as the problem does not seem to do with passing functions as parameters.
It is a little difficult to know exactly what you are trying to do, but you can certainly invoke public methods within your own try…catch
block.
public void ExistingMethod()
{
// bad code
// bad code
throw new NullReferenceException("The previous developers are always the problem.");
}
…
public void MyMethod(ComponentFromOldCode component)
{
try
{
component.ExistingMethod();
}
catch (NullReferenceException nre)
{
// do something
}
catch (Exception ex)
{
// do something
}
}
What you cannot do* is add error handling to existing calls to that function.
You may instead be able to add some high-level error handling that will at least give you an opportunity to log the exceptions and show a more graceful failure experience to your users.
*not reasonably

- 56,361
- 10
- 99
- 123
look into Delegates - http://msdn.microsoft.com/en-us/library/ms173171(v=vs.80).aspx

- 6,441
- 2
- 25
- 26
Look into Actions. They will allow you to pass an anonymous method as a parameter.
However, I don't think this is going to help you with your problem. You're probably going to want to refactor the codebase to have proper exception handling.

- 57,011
- 13
- 100
- 120
You can use Lambda Expression
class Program
{
private static int Sum(int a, int b)
{
return a + b;
}
private static int Multiply(int a, int b)
{
return a * b;
}
private static int GetResult(Func<int, int, int> solver, int a, int b)
{
try {
return solver(a, b);
} catch {
}
return 0; // your default return
}
static void Main(string[] args)
{
var a = 2;
var b = 3;
var sum = GetResult(Sum, a, b);
var multiply = GetResult(Multiply, a, b);
}
More information at
Lambda Expressions (C# Programming Guide)
http://msdn.microsoft.com/en-us/library/bb397687.aspx
Func Delegate

- 7,893
- 4
- 33
- 55

- 2,252
- 1
- 17
- 20