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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With