NGWS SDK Documentation  

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

throw

The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution. The throw statement takes the form:

throw [expression];

where:

expression
The exception object. This is omitted when re-throwing the current exception object in a catch clause.

Remarks

The thrown exception is an object whose class is derived from System.Exception, for example:

class MyException : System.Exception {}
throw new MyException();

Usually the throw statement is used with try-catch or try-finally statements. When an exception is thrown, the program looks for the catch statement that handles this exception.

Example

This example demonstrates how to throw an exception using the throw statement.

// throw example
using System;
public class ThrowTest {
   public static void Main() {
      string s = null;
      if (s == null) {
         throw(new ArgumentNullException());
      }
      Console.Write("The string s is null"); // not executed   
   }
}

Output

Caught exception: System.ArgumentNullException: argument can't be null at ThrowTest.Main()

Example

See the try-catch, try-finally and try-catch-finally examples.

See Also

Compare to C++ | C# Keywords | Exception Handling Statements | Grammar