Skip to content

Instantly share code, notes, and snippets.

@bronumski
Last active March 15, 2018 20:51
Show Gist options
  • Save bronumski/eaae7dca12aa7558d7d4f5bde14f3039 to your computer and use it in GitHub Desktop.
Save bronumski/eaae7dca12aa7558d7d4f5bde14f3039 to your computer and use it in GitHub Desktop.
C# Functional Try Catch Finally
public static int Main(string[] args) =>
Try
.Action(() => 0)
.WithCatch<Exception>(ex => 1})
.Finally(CleanUpMethod);
static class Try
{
public static Try<TResult> Action<TResult>(Func<TResult> act)
{
return new Try<TResult>(act);
}
}
class Try<TResult>
{
Func<TResult> action;
List<Func<Exception, TResult>> catchActions = new List<Func<Exception, TResult>>();
private Try(Func<TResult> action)
{
this.action = action;
}
public static Try<TResult> Action<TResult>(Func<TResult> act)
{
return new Try<TResult>(act);
}
public Try<TResult> WithCatch<TException>(Func<TException, TResult> act) where TException : Exception
{
catchActions.Add((Func<Exception, TResult>)act);
return this;
}
public TResult Finally(Action act)
{
try
{
return action();
}
catch(Exception ex)
{
foreach(var catchAction in catchActions)
{
return catchAction(ex);
}
throw ex;
}
finally
{
act();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment