Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception Handling in lambda Expression

Tags:

c#

lambda

Can anyone please explain how to handle exception handling in lambda expression. I know in Anonymous method we can use try catch method like,

Employee emp = listemp.Find(delegate(Employee employee) 
{ 
    try 
    { 
    if (number == 5) 
        throw new InvalidCastException(); 
    } 

    catch (Exception ex) 
    { 
      MessageBox.Show(ex.ToString()); 
    } 
    return employee.id == 101; 
} 

By converting above code into Lambda Expression we have,

Employee e1 = listemp.Find(x => x.id == 101); 

My question is: Can we implement try catch with this expression?

like image 245
user2866116 Avatar asked Jan 08 '15 22:01

user2866116


People also ask

How do you handle exceptions in lambda expression?

A lambda expression body can't throw any exceptions that haven't specified in a functional interface. If the lambda expression can throw an exception then the "throws" clause of a functional interface must declare the same exception or one of its subtype.

Can lambda throw exception C++?

Lambda functors for throwing exceptions are created with the unary function throw_exception . The argument to this function is the exception to be thrown, or a lambda functor which creates the exception to be thrown.

Can we throw exception in functional interface?

A single functional interface that throws a checked exception is created ( CheckedValueSupplier ). This will be the only functional interface which allows checked exceptions. All other functional interfaces will leverage the CheckedValueSupplier to wrap any code that throws a checked exception.

What is the disadvantage of lambda expression in Java?

The big paradox of lambdas is that they are so syntactically simple to write and so tough to understand if you're not used to them. So if you have to quickly determine what the code is doing, the abstraction brought in by lambdas, even as it simplifies the Java syntax, will be hard to understand quickly and easily.


1 Answers

Sure. Lambda expressions are just methods, so you can write:

listemp.Find(x => 
{
   bool found = false;
   try
   {
      found = x.id == 101;
   }
   catch (Exception ex) { }
   return found;
});

Note: I did NOT say it was OK to catch exceptions like that, this is for sample purposes only.

Of course, once your anonymous methods are this involved, you should probably be considering just using a proper method anyways.

like image 122
BradleyDotNET Avatar answered Oct 04 '22 14:10

BradleyDotNET