Setting the Error Message


The base class to all exceptions, System.Exception , has a property called Message that gives a brief description of the error. However, the Message property is readonly. So how do you set the error message of your custom exception objects?

To set the error message for custom error classes:

  1. Add a constructor to your custom exception class.

  2. In the body of the constructor call the base constructor passing the error message as a parameter ( Figure 11.21 ).

    Figure 11.21 Remember that the only time you can set a read-only property is in the constructor of the class. The Message property happens to be a read-only property.
     class AccountException : ApplicationException }    public int AccountNumber;    public AccountException() :  base(   "There was an error while accessing "   + "a bank account"  )    {    } } 

graphics/tick.gif Tip

  • A developer using your class may want to set the error message of your class instead of using the default error message you provide. To enable a developer to set a custom error message in your class add a constructor that accepts a string parameter, then pass the string in the constructor to the base constructor ( Figure 11.22 ).

    Figure 11.22 It's convenient to add several constructors to your exception class. Normally there should be a default constructor so that it's easy to create and throw the exception. But it's also good to add a constructor that lets the user modify the message, as the one in the figure.
     class AccountException : ApplicationException {    public int AccountNumber;    public AccountException(string msg) :  base(msg)  {    } } 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

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