Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using a Dictionary<TKey, TValue> with Exceptions

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading