Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to return only the function calls that do not throw exceptions with LINQ?

Tags:

c#

linq

I'm getting tossed into an existing codebase, and part of the job is to get the code gradually under test as I make updates. So it's a process of taking something old and ugly and making it nicer.

In this case, there is a code similar to this:

foreach (var thingamajigLocator in thingamajigLocators)
{
    Thingamajig thingamajig;
    try
    {
        thingamajig = thingamajigservice.GetThingamajig(thingamajigLocator);
    }
    catch
    {
        // exception logged further down, but is rethrown
        continue;
    }

    thingamajigCollection.Add(thingamajig);
}

It's ugly and in theory, if the exception is handled further down, it shouldn't be necessary to handle it here, but that's how the code is and currently, it's too much work to handle the service code.

I would love to do something like this:

thingamajigCollection = thingamajigLocators
                            .Select(tl => thingamajigservice.GetThingamajig(tl))
                            .Where( /* some condition that strips out the ones throwing exceptions */ );

Is this possible in any way? Any other suggestions? I can certainly leave the foreach with the try/catch, but it seems like it could be more elegant since I don't care what the actual exception is in this case. Which again, I know is horrible form, and will need to be addressed, but no time for it right now.

like image 653
McMuttons Avatar asked Jan 21 '23 07:01

McMuttons


1 Answers

Actually, there is no difference. Func is just a delegate. So, you can make it really straightforward:

thingamajigCollection = thingamajigLocators
                        .Select(tl => 
                             {
                             try
                                 {
                                     return thingamajigservice.GetThingamajig(tl);
                                 }
                             catch(Exception)
                                 {
                                     return null;
                                 }
                             })
                          .Where(t1 => t1!=null);

As an option you can wrap GetThingamajig in new method to catch exceptions there.

NOTE: As hmemcpy said swallowing exceptions isn't the best way to go. So, you better try to redesign things.

like image 129
default locale Avatar answered May 23 '23 16:05

default locale