13.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. In some cases, however, 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 Exception of namespace System. When you create code that throws exceptions, they should be well documented, so that other developers who use your code will know how to handle them.

Good Programming Practice 13.1

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

 

Software Engineering Observation 13.4

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.

Class NegativeNumberException

Figures 13.613.7 demonstrate a user-defined exception class. NegativeNumber-Exception (Fig. 13.6) represents exceptions that occur when a program performs an illegal operation on a negative number, such as attempting to calculate its square root. According to Microsoft’s “Best Practices for Handling Exceptions” (bit.ly/Exceptions-BestPractices), user-defined exceptions should typically extend class Exception, 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.

Fig. 13.6 NegativeNumberException represents exceptions caused by illegal operations performed on negative numbers.

Alternate View

  1    // Fig. 13.6: NegativeNumberException.cs
  2    // NegativeNumberException represents exceptions caused by
  3    // illegal operations performed on negative numbers.
  4    using System;
  5
  6    public class NegativeNumberException : Exception
  7    {
  8       // default constructor
  9       public NegativeNumberException()
 10          : base("Illegal operation for a negative number")
 11       {
 12          // empty body
 13       }
 14
 15         // constructor for customizing error message
 16         public NegativeNumberException(string messageValue)
 17            : base(messageValue)
 18         {
 19             // empty body
 20         }
 21
 22         // constructor for customizing the exception's error
 23         // message and specifying the InnerException object
 24         public NegativeNumberException(string messageValue, Exception inner)
 25            : base(messageValue, inner)
 26         {
 27            // empty body
 28         }
 29    }

NegativeNumberExceptions most frequently occur during arithmetic operations, so it seems logical to derive class NegativeNumberException from class ArithmeticException. However, class ArithmeticException derives from class SystemException—the category of exceptions thrown by the CLR. Per Microsoft’s best practices for exception handling, user-defined exception classes should inherit from Exception rather than SystemException. In this case, we could have used the built-in ArgumentOutOfRangeException class (introduced in Chapter 10), which is recommended in the best practices for invalid argument values. We create our own exception type here simply for demonstration purposes.

Using Class NegativeNumberException

Class SquareRootTest (Fig. 13.7) demonstrates our user-defined exception class. The app enables the user to input a numeric value, then invokes method SquareRoot (lines 40–52) 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’d like to prevent the user from calculating the square root of a negative number. If the numeric value that the user enters is negative, method SquareRoot throws a NegativeNumberException (lines 45–46). Otherwise, SquareRoot invokes class Math’s method Sqrt to compute the square root (line 50).

Fig. 13.7 Demonstrating a user-defined exception class.

Alternate View

  1    // Fig. 13.7: SquareRootTest.cs
  2    // Demonstrating a user-defined exception class.
  3    using System;
  4
  5    class SquareRootTest
  6    {
  7       static void Main(string[] args)
  8       {
  9          var continueLoop = true;
 10
 11          do
 12          {
 13              // catch any NegativeNumberException thrown
 14              try
 15              {
 16                  Console.Write(
 17                     "Enter a value to calculate the square root of: ");
 18                  double inputValue = double.Parse(Console.ReadLine());
 19                  double result = SquareRoot(inputValue);
 20
 21                   Console.WriteLine(
 22                      $"The square root of {inputValue} is {result:F6}
");
 23                   continueLoop = false;
 24              }
 25              catch (FormatException formatException)
 26              {
 27                 Console.WriteLine("
" + formatException.Message);
 28                 Console.WriteLine("Please enter a double value.
");
 29              }
 30              catch (NegativeNumberException negativeNumberException)
 31              {
 32                 Console.WriteLine("
" + negativeNumberException.Message);
 33                 Console.WriteLine("Please enter a non-negative value.
");
 34              }
 35          } while (continueLoop);
 36       }
 37
 38       // computes square root of parameter; throws
 39       // NegativeNumberException if parameter is negative
 40       public static double SquareRoot(double value)
 41       {
 42           // if negative operand, throw NegativeNumberException
 43           if (value < 0)
 44           {
 45              throw new NegativeNumberException(                               
 46                 "Square root of negative number not permitted");              
 47           }
 48           else
 49           {
 50              return Math.Sqrt(value); // compute square root
 51           }
 52       }
 53    }

             Enter a value to calculate the square root of: 30
             The square root of 30 is 5.477226

             Enter a value to calculate the square root of: hello

             Input string was not in a correct format.
             Please enter a double value.

             Enter a value to calculate the square root of: 25
             The square root of 25 is 5.000000

             Enter a value to calculate the square root of: -2

             Square root of negative number not permitted
             Please enter a non-negative value.

             Enter a value to calculate the square root of: 2
             The square root of 2 is 1.414214

When the user inputs a value, the try statement (lines 14–34) attempts to invoke SquareRoot using the value input by the user. If the user input is not a number, a Format-Exception occurs, and the catch block in lines 25–29 processes the exception. If the user inputs a negative number, method SquareRoot throws a NegativeNumberException (lines 45–46); the catch block in lines 30–34 catches and handles this type of exception.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset