Вопрос

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.

Другие советы

You should do something like this:

SomeType someVariable;
try {
  someVariable = getVariableOfSomeType();
}
catch {
  throw new Exception();
}
SomeType someVariable = null;

try
{
    someVariable = GetVariableOfSomeType();
}
catch(Exception e)
{
    // Do something with exception

    throw;
}

You can try this

try 
{
    SomeType someVariable = return getVariableOfSomeType();
} 
catch { throw; }
SomeType someVariable = null;

try
{
    //try something, if fails it move to catch exception
}
catch(Exception e)
{
    // Do something with exception

    throw;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top