[Previous] [Contents] [Next]

Throwing an Exception

When a method needs to notify the calling method that an error has occurred, it uses the throw keyword in the following manner: -

throw statement:
throw expressionopt;

We'll get into the different ways in which you can throw exceptions a bit later. For now, it's enough to realize that when you throw an exception, you're required to throw an object of type System.Exception (or a derived class). Following is an example of a method that has determined that an unrecoverable error has occurred and that it needs to throw an exception to the calling method. Notice how it instantiates a new System.Exception object and then throws that newly created object back up the call stack.

public void SomeMethod()
{
// Some error determined.
throw new Exception();
}

[Previous] [Contents] [Next]