0

We want to get user defined data that has been caused exception eg. Index out of bound exception.

try
{
    int[] list = new int[2];
    list[0] = 1;
    list[1] = 2;
    list[3] = 3;
    Console.WriteLine(list[4]);
}
catch (Exception ex)
{
    /* Expected
     1) Line Number :5
     2) Method Name: SearchArray()
     3) Data: 3 // object specifically
     4) excetion message:ArrayIndexOutOfBound Exception.
    */
    StackTrace st = new StackTrace(ex, true);
    StackFrame frame = st.GetFrame(0);

    var data = ex.StackTrace;
    var tr = ex.HResult;
}

In this scenario, we want to get List[3] value because this line is responsible for the exception (where list[3] will not be accessed).

Umesh Shende
  • 113
  • 2
  • 11
  • you can use ex.Message to print your exception – Negi Rox Oct 16 '18 at 09:41
  • Do you want to get string "list[3] = 3;" somehow from exception object? – vasily.sib Oct 16 '18 at 09:44
  • I see your expectation now. What you asking is available from stack trace (source filename, line number, etc.), but will reliably work only in DEBUG builds because in RELEASE build some "optimization" mechanics take place, and some of your code may be even optimized-out. – vasily.sib Oct 16 '18 at 09:52
  • You cannot get the value of `list[3]` because it is undefined. The array `list` contains only two elements. – John Wu Oct 16 '18 at 10:00
  • no..ex.message does not give us proper data.i want the exact data when error triggered – Umesh Shende Oct 16 '18 at 10:08
  • Is this a duplicate of [How do I get the line number of an exception](https://stackoverflow.com/questions/3328990/c-sharp-get-line-number-which-threw-exception)? – John Wu Oct 16 '18 at 10:12
  • I dont want only line number ..i want the object of data that has been exception trigger. – Umesh Shende Oct 16 '18 at 10:16

1 Answers1

0

Since scope of your code is outside catch statement, you cannot access the object there. As an alternate you can user StackTrace of exception. It will give you line number after column ":". You can use it. however, It will be Line number of class where error is occurred and not the exact function.

  • can i get object in this e.g. list in catch without passing list in the catch. – Umesh Shende Oct 16 '18 at 10:13
  • No its not possible as list is defined in try. In order to access it in catch, you need to define your object outside of try.int[] list = new int[2]; try { list[0] = 1; list[1] = 2; list[3] = 3; Console.WriteLine(list[4]); } catch (Exception ex) {Error Handling} – Hardiksinh Jadeja Oct 16 '18 at 10:14
  • if list define out side of try then how do we get that ? – Umesh Shende Oct 16 '18 at 10:17
  • Exception will not give you exact object but access to object. You need to identify the error on mentioned line number. As the error in your code is logical not a compile time error. Logical error are like doing Multiplication where you are asked to do a subtraction. Hope it clarifies. – Hardiksinh Jadeja Oct 16 '18 at 10:30