I want to do something like this in C#. I think this is possible using Delegates or Anonymous Methods. I tried but I couldn't do it. Need help.
SomeType someVariable = try {
return getVariableOfSomeType();
} catch { Throw new exception(); }
You can create a generic helper function:
static T TryCatch<T, E>(Func<T> func, Func<E, T> exception)
where E : Exception {
try {
return func();
} catch (E ex) {
return exception(ex);
}
}
which you can then call like so:
static int Main() {
int zero = 0;
return TryCatch<int, DivideByZeroException>(() => 1 / zero, ex => 0);
}
This evaluates 1 / zero
within the context of TryCatch
's try
, causing the exception handler to be evaluated which simply returns 0.
I doubt this will be more readable than a helper variable and try
/catch
statements directly in Main
, but if you have situations where it is, this is how you can do it.
Instead of ex => 0
, you can also make the exception function throw something else.