locked
What type of Exception to Throw RRS feed

  • Question

  • I am not sure which exception to throw.  I've got a private backing field being used in a method and I want to throw an exception if it's not a positive number:

    private int transactionID;
            protected void btnBuildTransaction_Click(object sender, EventArgs e)
            {
                if(transactionID < 1)
                    throw new
            }
    C# Web Developer
    Wednesday, September 16, 2009 6:17 PM

Answers

  • ArgumentException (and its subclasses) is meant to be reserved for situations where an invalid argument value is passed to a method.  This is not the case in your scenario.  Instead, your object state does not permit an operation, which is the sort of scenario that InvalidOperationException is meant to cover.  See http://msdn.microsoft.com/en-us/library/ms229007.aspx for details.
    • Marked as answer by nobugz Wednesday, September 16, 2009 8:43 PM
    Wednesday, September 16, 2009 7:24 PM

All replies

  • ArgumentException


    This is the exception to use if a parameter is not a valid option.

    Reed Copsey, Jr. - http://reedcopsey.com
    Wednesday, September 16, 2009 6:22 PM
  • that's actually the one I went with.  Thanks.
    C# Web Developer
    Wednesday, September 16, 2009 6:36 PM
  • ArgumentException (and its subclasses) is meant to be reserved for situations where an invalid argument value is passed to a method.  This is not the case in your scenario.  Instead, your object state does not permit an operation, which is the sort of scenario that InvalidOperationException is meant to cover.  See http://msdn.microsoft.com/en-us/library/ms229007.aspx for details.
    • Marked as answer by nobugz Wednesday, September 16, 2009 8:43 PM
    Wednesday, September 16, 2009 7:24 PM
  • I suppose you're correct, here.  The state of the object is invalid in this case.

    Realistically, the method or property that sets transactionID should have the ArgumentException (or ArgumentOutOfRangeException) thrown at that point, to prevent the invalid state from being possible.

    Reed Copsey, Jr. - http://reedcopsey.com
    Wednesday, September 16, 2009 9:39 PM