Manually throw an exception. : Exception Throw « Language Basics « C# / CSharp Tutorial






The general form is:

throw exceptOb;

The exceptOb must be an object of an exception class derived from Exception.

using System; 
 
class MainClass { 
  public static void Main() { 
    try { 
      Console.WriteLine("Before throw."); 
      throw new DivideByZeroException(); 
    } 
    catch (DivideByZeroException) { 
      // catch the exception 
      Console.WriteLine("Exception caught."); 
    } 
    Console.WriteLine("After try/catch block."); 
  } 
}
Before throw.
Exception caught.
After try/catch block.








1.22.Exception Throw
1.22.1.Manually throw an exception.
1.22.2.Rethrow an exception
1.22.3.Throw Exception from a function
1.22.4.Wrap exception in another one, adding additional context
1.22.5.Throw Exception in finally statement
1.22.6.Creating and throwing an exception object