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
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. |