Exception opinions?

I'm just busy writing a dialog box which needs a property to be set before ShowDialog is called. In the OnLoad, I'm checking whether it's been set and throwing an exception if it hasn't. Question is: which exception is most appropriate I'm leaning towards InvalidOperationException.

Of course, I could change the dialog's constructor to take the value as an argument, but I've got a notion that dialogs should provide a parameterless constructor --- is that right, or did I dream it




Answer this question

Exception opinions?

  • dickP

    Please help my imagination, since I am constrained to think that the default value of the underlying type would be a ‘reasonable’ value If the type is a ‘pointer’ to a class or struct, I am stuck thinking of a ‘blankClass’ as a constant instance.



  • Alejandro B

    So would I, but I'm not the only programmer working on this project.

  • Michael Springer

    The dialog cannot usefully instantiate a default instance of the class whose properties it is modifying, and it would not make sense for the dialog to be displayed without a properly instantiated class. It is up to the calling process to create an instance of that class with the necessary values, and pass it to the dialog. If the dialog is called without specifying an instance of the class, that is a coding error, hence the need for an exception.

  • rf09

    Why not provide two constructors: the first without arguments, which calls the second with a default value Then you can call it either way.



  • wandasoozq

    I can't: it's not logically possible to display the dialog unless the property has been set, and there is no possible default value.

  • Richard Watts

    A parameterless constructor is only important if you want to use the dialog on the designed (i.e., drag the dialog onto another form to create a member field of that dialog's type). Otherwise, requiring the user to pass a value in the constructor may be the way to go.
  • Gobi N

    Thanks, that's clarified that for me.

  • Demonslayer

    I see.

    Since this parameter would be ‘user data’ of a sort, I would validate it before I let it get anywhere near a dialog box.



  • Cammyr

    Even if you do not provide a default construtor, the argument passed to the constructor may still be invalid, in which case you could throw an ArgumentException. From MSDN "The exception that is thrown when one of the arguments provided to a method is not valid.".
  • surfguy0021

    You could also throw a custom exception:

    public class MyCustomDialogExceptionNeedsABetterName : System.Exception
    {
    Some properties describing error
    }


  • Exception opinions?