Exception handling with lambda/linq statements

exception handling in linq c#
handle null exception in linq c
how to handle null in linq query
linq select
entity framework exception handling best practices
c# exception handling best practices
c# catch all exceptions
linq join null reference exception

I have the following statement that I am trying to use a try-catch block with

var val= db.shops.where(x=>×.id==ID).Select (a=>a.address).First();

I tried following but has many issues won't even compile.

var val=db.shops.Where(x=> 
  {
    try 
    {
        (x.Id==ID).Select(a=>a.address).First();
    }
    catch(ex)
    {
      return ex;
    }
  }

Please let me know how can I handle the exception in this statement Thanks. Note: writing this question from mobile phone can't format code. Apologize for it.


You should place the try around your original statement:

try
{
   var val= db.shops.where(x=>×.id==ID).Select (a=>a.address).First();
}
catch (Exception ex)
{
   return ex; //I assume the return type here is wrong.  Maybe return null?
}

However, there's nothing about that line that should require a try/catch. Try this:

var val= db.shops.where(x=>×.id==ID).Select(a=>a.address).FirstOrDefault();

The FirstOrDefault will return null if there are no results.

Handle exceptions in query expressions (LINQ in C#), Example. The following example shows how to move exception handling code outside a query expression. This is only possible when the method  Handle exceptions in query expressions. 12/01/2016; 2 minutes to read +2; In this article. It's possible to call any method in the context of a query expression. However, we recommend that you avoid calling any method in a query expression that can create a side effect such as modifying the contents of the data source or throwing an exception.


Everything inside brackets ({ }) need to have 'regular' block syntax, so return is required here:

...
.Where
(x=> 
  {
    try 
    {
        return (x.Id == ID);
    }
    catch(ex)
    {
      throw;
    }
  }
)
.Select(a=>a.address)
.First(); // Or FirstOrDefault if you expect this statement to yield no result.

As you see, the Where is more like a regular statement now. The Select is moved to outside the Where. If you need exception handling in there, you have to do the same as in the Where block now. Last, return ex is probably meant to be throw ex, which should be throw in this case to preserve call stack.

Exception handling with lambda/linq statements, exception handling in linq c# handle null exception in linq c how to handle null in linq query handle exceptions in lambda expression linq select entity framework  Exception handling with lambda/linq statements. 4234 views December 2018 c# 8 . JD. J. Davidson December 2018 If you need exception handling in there,


...that I am trying to use try catch block with

I am guessing you probably meant to write FirstOrDefault based on where you want the try/catch. In the sample code you have provided I see no reason to try to make a catch block into one of the lambda statements. The best thing to do would be to simply use FirstOrDefault as that is the reason why you might get an exception in the code shown.

var address = db.shops.FirstOrDefault(x => ×.id == ID)?.Address;
if(address == null)
  // nothing was found or address is null, do something else

Or similar code closer to what you had without my "optimization"

var shop = db.shops.FirstOrDefault(x => ×.id == ID);
if(shop == null) {
  // nothing was found, do something else
}
var address = shop.address;

The other reason not to use try/catch is that it can't be translated into SQL and the variable name db which is the container for the shops collection which leads me to believe you are using EF or some other ORM. So even if you were to fix the syntax and your code with added try/catch block compiles you will get a run time error later when you execute the lambda.

Using Statement lambda in exception handling, First of all, you should copy the reference of action delegate instance before invoking it to prevent threading issues, like this: private void ExecutionAction(​Action  In order to use LINQ queries in C #, we have to include a reference to System.Core.dll and to include the namespace System.Linq in the beginning of the C# program. Data Sources with LINQ To define the data source (collection, array and so on), we have to use the keywords from and in and a variable for the iteration of the collection (the


Language Integrated Query (LINQ) and Lambda Expressions, If there were multiple arguments, then the lambda expression could look like Expressions" /> <add Number="5" Title="Debugging and Exception Handling"  In Java, we can only handle exceptions through the try-catch block, and this hasn’t changed for the lambda expression. Let’s say we’re going to develop a simple web crawler. The crawler will take a


How to Handle Checked Exceptions With Lambda Expression, This tutorial demonstrates how devs can handle checked exceptions in their projects using Java 8 and lambda expressions for cleaner, more  Should I include general exception handler to this, to be able to handle any unforeseen exceptions? Unfortunately, yes, you must do this. Does use of lambda statements in every method call (ExecutAction(() =>) degrade code readability? Some people say yes. You don't have to use lambdas. You can use ordinary static or instance methods.


Single Lambda Expression Sample in C#, Using Single, this LINQ (Lambda Expression) sample in C# retrieves a single element from each array, but from arrays Single(); } catch (Exception e) { Debug. A lambda expression cannot contain a goto, break, or continue statement if the target of that jump statement is outside the lambda expression block. It's also an error to have a jump statement outside the lambda expression block if the target is inside the block.