using System.Collections.Generic; namespace System.Extensions; public static class Try { public static Try Action(Func act) { return new Try(act); } } public class Try { private readonly Func action; private readonly List> catchActions = new List>(); internal Try(Func action) { this.action = action; } public static Try Action(Func act) { return new Try(act); } public Try Catch(Func act) where TException : Exception { this.catchActions.Add((Func)act); return this; } public TResult Run() { try { return this.action(); } catch (Exception ex) { foreach (var catchAction in this.catchActions) { return catchAction(ex); } throw; } } public TResult Finally(Action act) { if (act is null) { throw new ArgumentNullException(nameof(act)); } try { return this.action(); } catch (Exception ex) { foreach (var catchAction in this.catchActions) { return catchAction(ex); } throw; } finally { act(); } } }