Skip to content

Instantly share code, notes, and snippets.

@klumsy
Last active December 21, 2015 09:48
Show Gist options
  • Save klumsy/6287279 to your computer and use it in GitHub Desktop.
Save klumsy/6287279 to your computer and use it in GitHub Desktop.
try/catch while retraining strongly typed reference to an anonymous object.
public static class TryCatch
{
public static T Expression<T>(Func<T> lamda, Action<Exception> onException)
{
try
{
return lamda();
}
catch(Exception e)
{
onException(e);
return default(T);
}
}
}
//and example
Exception throwexception = null;
var results = TryCatch.Expression(
//TRY
() =>
{
//simulate exception happening sometimes.
if (new Random().Next(3) == 2)
{
throw new Exception("test this");
}
//return an anonymous object
return new { a = 1, b = 2 };
} ,
//CATCH
(e) => { throwexception = e;
//retrow if you wish
//throw e;
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment