views:

156

answers:

4

We sporadically get errors when we try to update a tool tip, like this

ToolTip.SetToolTip(myLabel, customDataStructure)

The error we get is a NullReferenceException: Object reference not set to an instance of an object

Does anyone know the cause of this?

Is a simple Try/Catch that eats the NullReferenceException a feasible option? We don't want our entire application to blow up when we get this.

+1  A: 

Try to test whether you're setting that var in any situation, using the debugger for example...

Is a simple Try/Catch that eats the NullReferenceException a feasible option?

That wouldn't solve the problem, it would hide it. A bad programming practice.

ktulur
+1  A: 

Ignoring exceptions is rarely if ever a good idea. The exception is thrown because something is wrong in the current implementation. By ignoring the exception the application basically proceeds in an undefined state and you will most likely see other weird effects due to the missing reference.

Since this is sporadic it could be a race condition issue, so you have to look carefully at the code to figure out if there are any situations in which the reference may be used before it is correctly initialized.

Brian Rasmussen
+1  A: 

I would guess that you're calling ToolTip.SetTooltip from an event handler and that handler sometimes fires before the label has been created. You should probably guard this with a check for the label being null and then make sure that the tool tip is initialised on the label's Load event.

You certainly shouldn't just catch the exception as this hides the problem.

Jeff Yates
A: 

I just ran into the same problem. It seems the exception is thrown from within the ToolTip.CreateHandle() method and it happens on MDI child window being disposed only. Before calling the SetToolTip(...) method, make sure the Disposing property of the parent form is false. Anyway, the form is being disposed, so you don't really care about the tooltips anymore...