Home > Back-end >  Using a Dictionary<TKey, TValue> with Exceptions
Using a Dictionary<TKey, TValue> with Exceptions

Time:10-21

I'm trying to figure out how I can save Exceptions within a dictionary in c#.

For example, I try:

Dictionary<Exception, Exception> myCustomExceptions = new() 
{
    { DbUpdateException, CustomExceptionX },
    { InvalidOperationException, CustomExceptionY }
}

Then I try to do something like this:

try
{
    ...
}
catch (Exception exception)
{
    throw myExceptions[exception];
}

But this however does not work unfortunately... Can someone please help me with this particular issue?

CodePudding user response:

You need to store a factory which can make new exception instances on demand.

Dictionary<Type, Func<Exception>> myCustomExceptions = new() 
{
    { typeof(DbUpdateException), () => new CustomExceptionX() },
    { typeof(InvalidOperationException), () => new CustomExceptionY() }
}

try
{
    ...
}
catch (Exception exception)
{
    var exceptionType = exception.GetType();
    var factory = myExceptions[exceptionType];
    var ex = factory();
    throw ex;
}
  • Related