C Sharp

Basic Exception-Handling Syntax

Exception handling consists of only four keywords: try, catch, throw, and finally. The way the keywords work is simple and straightforward. When a method fails its objective and cannot continue-that is, when it detects an exceptional situation-it throws an exception to the calling method by using the throw keyword. The calling method, assuming it has enough context to deal with the exception, then receives this exception via the catch keyword and decides what course of action to take. In the following sections, we'll look at the language semantics governing how to throw and catch exceptions as well as some code snippets that will illustrate how this works.

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();

by BrainBellupdated