Consider a situation where I have three (or more) ways of performing a calculation, each of which can fail with an exception. In order to attempt each calculation until we f
using System;
namespace Utility
{
///
/// A helper class for try-catch-related functionality
///
public static class TryHelper
{
///
/// Runs each function in sequence until one throws no exceptions;
/// if every provided function fails, the exception thrown by
/// the final one is left unhandled
///
public static void TryUntilSuccessful( params Action[] functions )
{
Exception exception = null;
foreach( Action function in functions )
{
try
{
function();
return;
}
catch( Exception e )
{
exception = e;
}
}
throw exception;
}
}
}
And use it like so:
using Utility;
...
TryHelper.TryUntilSuccessful(
() =>
{
/* some code */
},
() =>
{
/* more code */
},
calc1,
calc2,
calc3,
() =>
{
throw NotImplementedException();
},
...
);