Properties and Exceptions

   

When a property value is to be changed and there is a possibility that the new value might not be valid, the function obtaining the value should detect the invalid value and throw an exception so that the user can enter a valid value. Where can the property value be changed? It can be requested to change from one of three places: from a property editor dialog, from a property editor, and from the property itself at runtime. The relationship between the three is shown in Figure 5.2. Note that the parameter to the SetValue() method is a const AnsiString even though it is pass- by-value . This only restricts Value from being modified within SetValue() . This is contrary to the normal use of const , where the main purpose of the keyword is to indicate that the argument passed to the function will not be modified. With pass-by-value, the argument is copied so it will not be modified in any way. If an error occurs, throwing an exception is the only appropriate way of informing the user. The other set methods can also be written using this approach, that is, pass-by-value variables declared as const .

Figure 5.2. Exceptions thrown when editing a property.

graphics/05fig02.gif

From Figure 5.2 it can be seen that the set method for the property, in this case SetColor() , is ultimately called every time (unless an exception is thrown). It can then be tempting to detect only the validity of the property value at this stage and throw an exception from here. Remember that the purpose of throwing the exception is to detect the error and allow the user to enter a new value. By the time an exception is thrown from the property's set method, the user's edit operation is most likely finished. This might mean redisplaying a dialog or other inconveniences. You should throw an exception at the source of the error. Throwing an exception only from the property editor (or property editor dialog) is also no good because the property editor will not be used at runtime, letting invalid values silently cause havoc. The solution is to throw an exception from the point of error. It might not be the easiest solution to implement, but it is the most robust.


   
Top


C++ Builder Developers Guide
C++Builder 5 Developers Guide
ISBN: 0672319721
EAN: 2147483647
Year: 2002
Pages: 253

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net