Exception troubles

desmo

Member
Joined
Jan 3, 2018
Messages
14
Programming Experience
Beginner
In my small, simple Forms application I'm experiencing a lot of Exeptions which I'm trying to handle. Some are apparently related to .NET and hence out of my control. But some are related to my code. Here's an example:

C#:
for (int i = 0; i < userPanel.RowCount * userPanel.RowCount - 1; i++) {
    try {
        if (!string.IsNullOrWhiteSpace(userPanel.GetControlFromPosition(1, i).Text)) {
            instances.Add(new GCDriver(websiteTextBox.Text.ToString()));
            SiteLogin.AuthWindow.LoginUser(userPanel.GetControlFromPosition(1, i).Text.ToString(),
                                                             userPanel.GetControlFromPosition(2, i).Text.ToString());
        }
    } catch (NullReferenceException) { }
}

This code, which just reads the contents of a row of TextBoxes and instanciates another class if they're not empty, gives the following exception:

NullReferenceException occurred
Additional information: Object reference not set to an instance of an object.

Troubleshooting tips:
Check to determine if the object is null before calling the method.
Use the "new" keyword to create an object instance.


But I AM checking if it's null. I've got a try-catch for NullReferenceException, and I'm also checking for null or whitespace in the if-statement. What more can I do? Is this how it's supposed to be? Is the exception just a notification?
 
If you're testing whether something is null and only using it if it's not and you still get a NullReferenceException then obviously something other than what you're testing is null. Comment out the exception handling and let the debugger catch the exception. When the debugger breaks on the exception, use the tools the debugger provides to examine every reference on the offending line to see which one is null. Don't make assumptions. Examine the actual data.
 
Hm. If I remove the try-catch in the example code, I get a new exception in the Program.cs file: System.Reflection.TargetInvocationException.
This is the code where that happens:

C#:
static void Main() {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new MainForm());
}

And this crashes the application. If I try catching it, the aplication still crashes (but the error is not thrown, of course).
 
It's located in the main thread of the class Program.cs, which is created automatically by Visual Studio. I'm not sure if changing any of that is a good idea?

C#:
static void Main() {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new MainForm());
}
 

Latest posts

Back
Top Bottom