Generating an Exception


As the author of a class, you may want to generate your own exceptions to notify other developers of various error conditions. You can choose to write your own exception classes (as in the section "Declaring Your Own Exceptions"), or you can choose to generate a predefined Microsoft error like DivideByZeroException or ArgumentNullException .

To throw an exception:

  1. Create a new instance of the exception class you want to generate and store it in a variable.

  2. In the next line type throw followed by the name of the variable that holds the instance of the exception class followed by a semicolon ; ( Figure 11.23 ).

    Figure 11.23 The only types of objects that can be thrown are objects that derive from System.Exception .
     class AccountOverdrawnException : ApplicationException {    public int AccountNumber;    public int Amount;    public AccountOverdrawnException()    {    }    public AccountOverdrawnException(    string msg) : base(msg)    {    } } class Checking {    public int AccountNumber;    private double Balance;    public void MakeWithdrawal(    double Amount)    {       if (Amount > Balance)       {  AccountOverdrawnException ex =   new AccountOverdrawnException();   throw ex;  }    } } 

graphics/tick.gif Tips

  • You can also combine the creation of the new exception and the throw statement into one statement ( Figure 11.24 ).

    Figure 11.24 If you don't need to set any of the properties of the exception, it's easier to combine the throw with the new command.
     class Checking {    public int AccountNumber;    private double Balance;    public void MakeWithdrawal(    double Amount)    {       if (Amount > Balance)       {  throw new   AccountOverdrawnException();  }    } } 
  • If you use the throw statement within the try portion of a try/catch block the catch portion of the block will catch the exception. In other words you will catch your own exception.

  • If you throw an exception within the catch portion of a try/catch block, the function will exit and the exception will be passed on to the caller of the function.

  • Don't use an exception in the try section of your code as a means to execute code in the catch section. Some developers have used this technique in the pastthey write code as part of a catch block, then in certain instances they generate a " phony " error to trigger that code. Shame on them! This is a poor practice because exceptions are only intended to report error conditions.




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