Throwing Exceptions

Time for a more structured look at working with exceptions. We’ll start with the act of throwing exceptions to signal an error condition. Not surprisingly, throwing an exception is done using the throw keyword, specifying an instance of an exception type. For example:

void DisplayUserProfile(string user){    if (user == null)        throw new ArgumentNullException("user");    if (user == "")        throw new ArgumentException("exception");    if (!Profiles.Exists(user))        throw new UserNotFoundException(user);    // Do real work here.}

The third exception type used here is a custom exception type, something we explore later. What matters here is the syntax of the throw statement, which is, ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.