Skip to content

Instantly share code, notes, and snippets.

@ATikadze
Last active June 19, 2022 18:05
Show Gist options
  • Select an option

  • Save ATikadze/a34505666e6bc2b2bded11ca827e07b1 to your computer and use it in GitHub Desktop.

Select an option

Save ATikadze/a34505666e6bc2b2bded11ca827e07b1 to your computer and use it in GitHub Desktop.
C#: Easily manage exceptions
public class ExceptionManager
{
private readonly List<Exception> _thrownExceptions;
private static ExceptionManager _instance;
private ExceptionManager(int maxExceptions, Action onFinalException, Action<Exception> onExceptionThrown = null)
{
MaxExceptions = maxExceptions;
CurrentExceptions = 0;
OnExceptionThrown = onExceptionThrown;
OnFinalException = onFinalException;
_thrownExceptions = new List<Exception>();
}
public static ExceptionManager Instance => _instance;
public int MaxExceptions { get; set; }
public int CurrentExceptions { get; private set; }
public Action<Exception> OnExceptionThrown { get; set; }
public Action OnFinalException { get; set; }
public IReadOnlyList<Exception> ThrownExceptions => _thrownExceptions;
public static void Instantiate(int maxExceptions, Action onFinalException, Action<Exception> onExceptionThrown = null)
{
_instance = new ExceptionManager(maxExceptions, onFinalException, onExceptionThrown);
}
public void Reset()
{
CurrentExceptions = 0;
_thrownExceptions.Clear();
}
public void ExceptionThrown(Exception exception)
{
CurrentExceptions++;
_thrownExceptions.Add(exception);
OnExceptionThrown?.Invoke(exception);
if (CurrentExceptions == MaxExceptions)
{
OnFinalException();
}
}
}
public class Program
{
private static void Main(string[] args)
{
ExceptionManager.Instantiate(5, OnFinalException);
ExceptionManager.Instance.OnExceptionThrown = ex =>
{
Console.WriteLine("Exception was thrown: " + ex.Message);
};
while (true)
{
try
{
Console.Write("Enter a number: ");
var input = Console.ReadLine();
int.Parse(input);
Console.WriteLine("Success!");
}
catch (Exception ex)
{
ExceptionManager.Instance.ExceptionThrown(ex);
}
}
}
private static void OnFinalException()
{
Environment.Exit(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment