views:

523

answers:

3

Example:

myEnumerable.Select(a => ThisMethodMayThrowExceptions(a));

How to make it work even if it throws exceptions? Like a try catch block with a default value case an exceptions is thrown...

+7  A: 
myEnumerable.Select(a => 
  {
    try
    {
      return ThisMethodMayThrowExceptions(a));
    }
    catch(Exception)
    {
      return defaultValue;
    }
  });

But actually, it has some smell.

About the lambda syntax:

x => x.something

is kind of a shortcut and could be written as

(x) => { return x.something; }
Stefan Steinegger
magic curly brackets
Jader Dias
+5  A: 

Call a projection which has that try/catch:

myEnumerable.Select(a => TryThisMethod(a));

...

public static Bar TryThisMethod(Foo a)
{
     try
     {
         return ThisMethodMayThrowExceptions(a);
     }
     catch(BarNotFoundException)
     {
         return Bar.Default;
     }
}

Admittedly I'd rarely want to use this technique - it feels like an abuse of exceptions in general, but sometimes there are APIs which leave you know choice.

(I'd almost certainly put it in a separate method rather than putting it "inline" as a lambda expression though.)

Jon Skeet
+1  A: 

When dealing with LINQ you'll commonly find scenarios where your expression could produce undesired side effects. As Jon said, the best way to combat these sort of problems is to have utility methods your LINQ expression can use that will handle these gracefully and in a fashion that won't blow up your code. For example, I have a method I've had to use time to time which wraps a TryParse to tell me if something is a number. There are many other examples of course.

One of the limitations of the expression syntax is that there are a lot of things it can't do either gracefully or even at all without breaking execution out of the expression temporarily to handle a given scenario. Parsing a subset of items in an XML file is wonderful example. Try parsing a complex parent collection with child subsets from an XML file within a single expression and you'll soon find yourself writing several expression pieces that all come together to form the entire operation.

Nathan Taylor