Section 12.8. User-Defined Exception Classes


12.8. User-Defined Exception Classes

In many cases, you can use existing exception classes from the .NET Framework Class Library to indicate exceptions that occur in your programs. However, in some cases, you might wish to create new exception classes specific to the problems that occur in your programs. User-defined exception classes should derive directly or indirectly from class ApplicationException of namespace System.

Good Programming Practice 12.1

Associating each type of malfunction with an appropriately named exception class improves program clarity.


Software Engineering Observation 12.3

Before creating a user-defined exception class, investigate the existing exceptions in the .NET Framework Class Library to determine whether an appropriate exception type already exists.


Figures 12.6 and 12.7 demonstrate a user-defined exception class. Class NegativeNumberException (Fig. 12.6) is a user-defined exception class representing exceptions that occur when a program performs an illegal operation on a negative number, such as attempting to calculate its square root.

Figure 12.6. ApplicationException derived class thrown when a program performs an illegal operation on a negative number.

  1  ' Fig. 12.6: NegativeNumberException.vb  2  ' NegativeNumberException represents exceptions caused by  3  ' illegal operations performed on negative numbers.  4  Public Class NegativeNumberException : Inherits ApplicationException  5     ' default constructor                                      6     Public Sub New ()                                          7        MyBase.New("Illegal operation for a negative number")   8     End Sub ' New                                              9 10     ' constructor for customizing error message    11     Public Sub New(ByVal messageValue As String)   12        MyBase.New(messageValue)                    13     End Sub ' New                                  14 15     ' constructor for customizing the exception's error                      16     ' message and specifying the InnerException object                       17     Public Sub New(ByVal messageValue As String, ByVal inner As Exception)   18        MyBase.New(messageValue, inner)                                       19     End Sub ' New                                                            20  End Class ' NegativeNumberException 

Figure 12.7. SquareRootForm class throws an exception if an error occurs when calculating the square root.

  1  ' Fig. 12.7: SquareRootTest.vb  2  ' Demonstrating a user-defined exception class.  3  Public Class frmSquareRootTest  4     ' computes square root of parameter; throws  5     ' NegativeNumberException if parameter is negative  6     Public Function SquareRoot(ByVal value As Double) As Double  7        ' if negative operand, throw NegativeNumberException  8        If value < 0 Then  9           Throw New NegativeNumberException(_                10              "Square root of negative number not permitted") 11        Else 12           Return Math.Sqrt(value) ' compute square root 13        End If 14     End Function ' SquareRoot 15 16     ' obtain user input, convert to double, calculate square root 17     Private Sub btnSquareRoot_Click(ByVal sender As System.Object, _ 18        ByVal e As System.EventArgs) Handles btnSquareRoot.Click 19 20        lblOutput.Text = "" ' clear lblOutput 21 22        ' catch any NegativeNumberException thrown 23        Try 24          Dim result As Double = _ 25             SquareRoot(Convert.ToDouble(txtInput.Text)) 26 27          lblOutput.Text = result.ToString() 28        Catch formatExceptionParameter As FormatException 29           MessageBox.Show(formatExceptionParameter.Message, _ 30              "Invalid Number Format", MessageBoxButtons.OK, _ 31              MessageBoxIcon.Error) 32        Catch negativeNumberExceptionParameter As NegativeNumberException 33           MessageBox.Show(negativeNumberExceptionParameter.Message, _    34              "Invalid Operation", MessageBoxButtons.OK, _                35              MessageBoxIcon.Error )                                      36        End Try 37     End Sub ' btnSquareRoot_Click 38  End Class ' frmSquareRootTest 

(a)

(b)

(c)

(d)

According to Microsoft's "Best Practices for Handling Exceptions [Visual Basic]," user-defined exceptions should extend class ApplicationException, have a class name that ends with "Exception" and define three constructors: a parameterless constructor; a constructor that receives a String argument (the error message); and a constructor that receives a String argument and an Exception argument (the error message and the inner exception object). Defining these three constructors makes your exception class more flexible, allowing other programmers to easily use and extend it.

NegativeNumberExceptions most frequently occur during arithmetic operations, so it seems logical to derive class NegativeNumberException from class ArithmeticException. However, class ArithmeticException derives from class SystemExceptionthe category of exceptions thrown by the CLR. Recall that user-defined exception classes should inherit from ApplicationException rather than SystemException.

Class SquareRootForm (Fig. 12.7) demonstrates our user-defined exception class. The application enables the user to input a numeric value, then invokes method SquareRoot (lines 614) to calculate the square root of that value. To perform this calculation, SquareRoot invokes class Math's Sqrt method, which receives a Double value as its argument. Normally, if the argument is negative, method Sqrt returns NaN. In this program, we would like to prevent the user from calculating the square root of a negative number. If the numeric value that the user enters is negative, the SquareRoot method throws a NegativeNumberException (lines 910). Otherwise, SquareRoot invokes class Math's method Sqrt to compute the square root (line 12).

When the user inputs a value and clicks the Calculate Square Root button, the program invokes event handler SquareRootButton_Click (lines 1737). The try statement (lines 2336) attempts to invoke SquareRoot using the value input by the user. If the user input is not a valid number, a FormatException occurs, and the Catch block in lines 2831 processes the exception. If the user inputs a negative number, method SquareRoot throws a NegativeNumberException (lines 910); the Catch block in lines 3235 catches and handles this type of exception.




Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

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