0

in my Windows Forms app I keep getting an unhandled ArgumentException ("input array is longer than number of columns in table") in line 56 (within catch). For debugging purposes I'm trying to show a message box, but I always get the exception and the message box never shows.

  1. Why is the message box not shown?
  2. How can I get the current values of row.Length, errMsg etc. and print them somewhere where I can read them?

In the watch window it says "value not available at current pointer".

How can I print simple debugging information in Windows Forms apps, just like I would do in console apps?

P.S. The method below is run after a button is clicked in the forms app.

using System;
using System.Data;
using System.IO;
using System.Text;
using CsvHelper;
using System.Windows.Forms;

namespace ARautomat_visual {

    class Model {

        // read CSV-file to DataTable
        // hasHeader is passed as FALSE
        public static DataTable GetDataTableFromCsv (string file, bool hasHeader = true) {

            DataTable dataTable = new DataTable();

            using (TextReader infile = new StreamReader(file, Encoding.Default))
            using (CsvParser csv = new CsvParser(infile)) {
                csv.Configuration.Delimiter = ";";

                bool datevFormat = false;
                string[] row;

                for (int i = 0; (row = csv.Read()) != null; i++) {

                    if (i == 0) {

                        if (datevFormat == false && (row[0] == "EXTF" || row[0] == "DTVF")) {
                            datevFormat = true;
                            i--;
                        }
                        else if (hasHeader == true) {
                            try {
                                string errMsg = $"row.Length: {row.Length}\n";

                                foreach (DataColumn item in dataTable.Columns) {
                                    errMsg += $"{item.ColumnName}, ";
                                }

                                Program.TriggerError(errMsg);

                                for (int j = 0; j < row.Length; j++) {
                                    dataTable.Columns.Add(row[j]);
                                }
                            }
                            catch (Exception e) {
                                string errMsg = $"Fehler: {e.Message}; row.Length:     {row.Length.ToString()}; Columns:     {dataTable.Columns.ToString()}";    

                                MessageBox.Show("Mist!");
                                Program.TriggerError(errMsg);
                                throw; // this is line 56
                            }
                        }
                        else {
                            dataTable.Rows.Add(row);
                        }
                    }
                    else if (i > 0) {
                        dataTable.Rows.Add(row);
                    }
                }
            }

            return dataTable;                
        }
    }
}

Program.cs

static class Program {

    // print all warnings
    public static void PrintWarnings() {
      if (!String.IsNullOrEmpty(warningsTriggered)) {
        TriggerStatus(warningsTriggered, "Warnung");
      }
    }

    // print warnings, print errors, exit
    public static void TriggerError (string msg) {
      PrintWarnings();
      TriggerStatus("Fehler: " + msg + @"Programm wird nach Klick auf 'OK' beendet.", "Fehler");
      //Application.Exit();
      Form.ActiveForm.Close();
    }

}
Markus
  • 79
  • 1
  • 8
  • 1
    don't re-throw the exception. Remove throw from catch – apomene Apr 30 '18 at 11:59
  • Have you thought that can be an error in the line above? `string errMsg = $"Fehler: {e.Message}; row.Length: {row.Length.ToString()}; Columns: {dataTable.Columns.ToString()}";` What about the `row` is null or `dataTable`? Try to put `MessageBox` as first line in `catch` block – Ricardo Pontual Apr 30 '18 at 12:00
  • @apomene Doesn't help. Same exception, same line. – Markus Apr 30 '18 at 12:00
  • @RicardoPontual: still no `MessageBox` showing if moved to 1st line in `catch` block. And still same `Exception`. Possible that there is a error in the `string` line. But first I think I need to find out, how to print out debugging info in catch in general. – Markus Apr 30 '18 at 12:03
  • during debug mode on your pc it may through the error before the message but what happens if you tell it to keep running - doyou get the messagebox then? – BugFinder Apr 30 '18 at 12:08
  • @BugFinder: if I run it outside Visual Studio the program window stays open, but still no `MessageBox` – Markus Apr 30 '18 at 12:11
  • 1
    If you say that you do get an unhandled exception when you remove line 56 (ie do not rethrow) - then the exception cannot be from within the try block - which is why your message does not display. Implementing an unhandled exception handler for the application may be a solution. – PaulF Apr 30 '18 at 12:11
  • @PaulF I **do** get an unhandled exception at the end of the `catch` block and no `MessageBox`. I still do, even if I comment out all lines within `catch` except for the `MessageBox`, How do I create an unhandled exception handler? I was under the impression that `Exception` catches them all?! – Markus Apr 30 '18 at 12:18
  • Debugging is the best friend to figure out where and why the exception is happening. – Chetan Apr 30 '18 at 12:18
  • @ChetanRanpariya: sure! But how do I go about it in Visual Studio in this situation? Watch window doesn't help. So how can I check on the values of different variables when an exception has occured? – Markus Apr 30 '18 at 12:20
  • 1
    By debugging I mean putting break points and stepping thru the code. And how does the watch window doesn't help? You should carefully step thru the code in try block to see which line of code throws exception. – Chetan Apr 30 '18 at 12:22
  • Step through the code line by line - eventually you will find when the exception occurs. – PaulF Apr 30 '18 at 12:23
  • Exactly what do you mean when you say you get an unhandled exception at the end of the catch block - if you get to the end of the catch block then you have handled the exception. See this for [unhandled exception handler](https://www.google.co.uk/search?ei=ef_mWrrVI6TQgAbSxrLgCA&q=c%23+unhandled+exception+handler&oq=c%23+unhandled+exce&gs_l=psy-ab.1.1.0l9.6491.9915.0.11912.14.6.0.8.8.0.103.520.5j1.6.0....0...1c.1.64.psy-ab..0.14.766...0i67k1.0.Dhnvvm5Za2s) – PaulF Apr 30 '18 at 12:25
  • Im with @PaulF here if you remove the throw then the exception should be handled.. Unless the problem lies then in calling the triggerstatus.. – BugFinder Apr 30 '18 at 12:28
  • Have you put a break point on the MessageBox.Show line with all of the rest of the code deleted? – PaulF Apr 30 '18 at 12:37
  • You could also put all of the code inside the catch block into another try catch block to check for exceptions caused in that code. _"catch (Exception e) { try {MessageBox.Show("Mist!");} catch (Exception e2) {} }"_ – PaulF Apr 30 '18 at 12:44

2 Answers2

2

Turns out the problem was within the else-clause: I tried to add a new row to the empty dataTable without creating columns in beforehand.

I added the for-loop below and now the code runs fine.

else {

  for (int j = 1; j <= row.Length; j++) {
    dataTable.Columns.Add("Column " + j);
  }

  dataTable.Rows.Add(row);
}

What did confuse me a lot was the fact that Visual Studio was actually placing the exception symbol at the end of the catch-block, despite the fact that the else if-block wasn't even entered and the exception was actually thrown in the else-block.

Thanks to Chetan and PaulF for guiding me with debugging using break points!!

Markus
  • 79
  • 1
  • 8
  • Glad you resolved the problem. I recommend looking at the application level unhandled exception handler - it wont stop the application terminating but it does give a chance to get a stack trace that may be useful to locating the problem. The technique may be different for WPF & WinForms (or whatever platform) which is why I gave the Google link rather than being specific. – PaulF Apr 30 '18 at 13:59
0
catch (Exception e)
{
    string errMsg = $"Fehler: {e.Message}; row.Length: {row.Length.ToString()}; Columns: {dataTable.Columns.ToString()}";    

    MessageBox.Show("Mist!");
    Program.TriggerError(errMsg);
    throw; // this is line 56
}

Your problem is that you are using the throw keyword. The throw keyword is used to re-throw an exception. See this: What does "throw;" by itself do?

Sebastian Hofmann
  • 1,440
  • 6
  • 15
  • 21
Chimera
  • 149
  • 1
  • 13
  • If you read the comments you will see that this is the very first comment made & that OP said that this does NOT fix the problem. He also said removing all code other then MessageBox.Show did NOT resolve the problem. – PaulF Apr 30 '18 at 13:30
  • As @PaulF already pointed out: this does not fix the problem. Rather see my own solution below. – Markus Apr 30 '18 at 13:39