Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to catch MS Chart control exception

I can't figure out why I'm unable to catch an exception thrown by MS Chart control. I'm using Visual Studio 2010, with latest updates. Appreciating your help.

Here's how to re-produce the issue:

  • Create a new WinForms application
  • Add a reference to System.Windows.Forms.DataVisualization
  • On the main form drop a button and a chart control
  • Add the following code the form's constructor

        int[] x = new int[] { 1, 2, 3, 4, 5 };
        int[] y = new int[] { 5, 13, 4, 10, 9 };
        chart1.Series[0].Points.DataBindXY(x, y);
    
  • Add the following code to the button's click method

        try
        {
            chart1.Series[0].Label = "#VAL{";
        }
        catch
        {
            MessageBox.Show("Exception caught");
        }
    
  • Run the application
  • Click the button on the form

The catch block above is never executed. Instead the "InvalidOperationException" thrown by the invalid keyword use in the label string bubbles up to the application's Main method.

like image 815
veezi Avatar asked Jun 28 '26 13:06

veezi


1 Answers

This is not an uncommon failure mode for controls. At issue is that the property setter for the Label property doesn't perform enough checks to verify that the assigned value is legal. So this goes wrong when the property value actually gets used. Later, when the control paints itself. Readily visible in the call stack window, note how Chart.OnPaint() is on top of the stack. The debugger stops at Application.Run() because that's the last statement for which it actually has source code. So make sure you look up in the call stack.

There are countermeasures against this in Winforms, the Application.ThreadException event will fire. But that's turned off when you debug, a feature to help you diagnose exceptions. It is not practical anyway, an event handler for ThreadException can't fix a bug in the code. You can catch the exception, you'd have to force a repaint so the painting isn't delayed and will bomb while your try block is still in effect:

    private void button1_Click(object sender, EventArgs e) {
        try {
            chart1.Series[0].Label = "#VAL{";
            chart1.Refresh();
        }
        catch {
            MessageBox.Show("Exception caught");
        }
    }

But that's not a real fix either, it will just bomb again on the next repaint. Unless you re-assign the Label property in the catch block. The only real cure is to fix the code. If you allow the user to enter the label then this workaround should be good, just make sure to reset the label in the catch block.

like image 140
Hans Passant Avatar answered Jun 30 '26 01:06

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!