Throwing Exceptions

As you’ll see shortly, exceptions are objects provided by the .NET Framework. All exceptions are of type System.Exception or of types derived from System.Exception.

C# includes a number of predefined exception types that you can use in your own programs. (These are actually defined in the Base Class Library’s System namespace, and are therefore available to all .NET languages, not just C#.) These exception types include ArgumentNullException, InvalidCastException, and OverflowException, as well as many others. Most of them have obvious purposes, based on their name. For example, ArgumentNullException is thrown when an argument to a method is null when that is not an expected (or acceptable) value.

Most of the time, the predefined exceptions will be all you need for your program, but you can define custom exceptions if you need them. Microsoft suggests that all the exceptions you use in your program derive from System.Exception.

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.