42895

Catch exception inside Linq

Question:

I have this problem in my C#-code. I get an exception inside my Linq-code and would like to know how to catch it. <em>I have searched SO but cannot find any relevant issues.</em>

I have simplified my query to this:

var test = from values in myTable.AsEnumerable() select new valueSet { ID = values["ID"].ToString(), Number = values["Number"].ToString(), Name = this.getName(values["Number"].ToString()), }

Since I get an exception inside the query when running the function <strong><em>getName</em></strong> I want to be able to catch the exception and also which <strong><em>Number</em></strong> I am currently at. Something like this:

try { var test = from values in myTable.AsEnumerable() select new valueSet { ID = values["ID"].ToString(), Number = values["Number"].ToString(), Name = this.getName(values["Number"].ToString()), } catch (Exception ex) { //I want to use "Number" here! throw ex; }

I am aware of that I declare my test-variable inside the try but can I for each "linq-loop" store the current Number? Any suggestions?

Answer1:

To achieve this, you will have to use the "other" LINQ syntax that uses extension methods and lambdas:

var test = myTable.AsEnumerable().Select(values => { try { return new valueSet { ID = values["ID"].ToString(), Number = values["Number"].ToString(), Name = this.getName(values["Number"].ToString()), }; } catch(Exception ex) { throw new ApplicationException("cannot load number" + values["Number"].ToString()); } });

Answer2:

A quick test to show what can work. Define a custom exception class:

public class MyException : Exception { public MyException(TestClass testClass) { TestClass = testClass; } public TestClass TestClass { get; set; } }

For demonstration, I use a custom TestClass, but this would be your table:

public class TestClass { public int Id {get; set; } public int Number { get; set; } public string Name {get; set; } }

Your getName operation would look like:

public static string getName(TestClass testClass) { try { //functionality goes here throw new Exception(); // just for demo purposes, throw an exception here return testClass.Name; } catch (Exception ex) { throw new MyException(testClass); } }

And the main method that demonstrates how to catch the number:

static void Main(string[] args) { var list = new List<TestClass>() { new TestClass() { Id = 1, Name= "name", Number= 789} }; try { var test = (from values in list select new { Id = values.Id, Name = getName(values), }).ToList(); } catch (MyException ex) { //I want to use "Number" here! var number = ex.TestClass.Number; throw ex; } }

PS - don't mind the static keyword, this test was done in a console application.

Recommend

  • Problem serializing DecimalFormatSymbols in 2.3.4
  • Issue with static code in Android
  • mapping between two ontologies
  • Many to Many in Linq using Dapper
  • Multiple Left Join LINQ-to-entities
  • multidatatrigger with multibinding in ControlTemplate.Triggers
  • Problem with rejecting incoming call
  • Need code translation from VB to C#
  • Best practice to eliminate magic numbers within a member function
  • Exception creating JSON with LINQ
  • Cloud Code function running twice
  • OSX - always hide certain files
  • Linq Merge lists
  • Eliminate partial duplicate rows from result set
  • Tamper-proof configuration files in .NET?
  • Thread safety of a fluent like class using clone() and non final fields
  • How to run “Deployd” on port 80 instead of port 5000 in webserver.
  • Converting a WriteableBitmap image ToArray in UWP
  • Mysterious problem with floating point in LISP - time axis generation
  • How to know when stdin is empty if it contains EOF?
  • Exception “firebase.functions() takes … no argument …” when specifying a region for a Cloud Function
  • javascript inside java/jsp code
  • WinForms: two way TextBox problem
  • ActionScript 2 vs ActionScript 3 performance
  • Weird JavaScript statement, what does it mean?
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • How do you troubleshoot character encoding problems?
  • How can I estimate amount of memory left with calling System.gc()?
  • Apache 2.4 - remove | delete | uninstall
  • How to format a variable of double type
  • Android Studio and gradle
  • how does django model after text[] in postgresql [duplicate]
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Reading document lines to the user (python)
  • Binding checkboxes to object values in AngularJs
  • How can i traverse a binary tree from right to left in java?
  • How to Embed XSL into XML
  • Net Present Value in Excel for Grouped Recurring CF
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize
  • How to load view controller without button in storyboard?