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, as you can see, very straightforward. ...

Get C# 4.0 Unleashed 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.