Multiple Exception Types

Listing 10.1 throws a System.ApplicationException, not the System .Exception type demonstrated in Chapter 4. C# allows code to throw any type that derives (perhaps indirectly) from System.Exception.

The code for throwing any exception is simply to prefix the exception instance with the keyword throw. The type of exception used is obviously the type that best describes the circumstances surrounding the error that caused the exception.

For example, consider the TextNumberParser.Parse() method in Listing 10.1.

Listing 10.1. Throwing an Exception

 public sealed class TextNumberParser {   public static int Parse(string  textDigit)    {       string[] digitTexts =           { "zero", "one", "two", "three", "four",               "five", "six", "seven", "eight", "nine" };       int result = Array.IndexOf(           digitTexts, textDigit.ToLower());       if  (result < 0)       {            throw new ArgumentException(                                           "The argument did not represent a digit",                          "textDigit");                                             }       return result;   } }

Instead of throwing System.Exception, it is more appropriate to throw ArgumentException because the type itself indicates what went wrong and includes special parameters for identifying which parameter was at fault.

Three similar exceptions are ArgumentException, ArgumentNullException, and NullReferenceException. ArgumentNullException should be thrown for the inappropriate passing of null arguments. This is a special case of an invalid parameter exception that would more generally (when it wasn't null) be thrown as an ArgumentException or an ArgumentOutOfRangeException. NullReferenceException is generally something that only the underlying runtime will throw with an attempt to dereference a null. Instead of causing a NullReferenceException, programmers should check parameters for null before accessing them and then throw an ArgumentNullException, which can provide more contextual information such as the parameter name.

Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185 © 2008-2017.
If you may any questions please contact us: