Updated: September 2008
The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution.
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.
You can also rethrow a caught exception using the throw statement. For more information and examples, see try-catch and Throwing Exceptions.
This example demonstrates how to throw an exception using the throw statement.
public class ThrowTest2 { static int GetNumber(int index) { int[] nums = { 300, 600, 900 }; if (index > nums.Length) { throw new IndexOutOfRangeException(); } return nums[index]; } static void Main() { int result = GetNumber(3); } } /* Output: The System.IndexOutOfRangeException exception occurs. */
See the try-catch, try-finally, and try-catch-finally examples.
For more information, see the following sections in the C# Language Specification:
5.3.3.11 Throw statements
8.9.5 The throw statement
Date
History
Reason
September 2008
Fixed example code.
Customer feedback.
<# .SYNOPSIS Shows throwing an exception in a function, caught in caller. .DESCRIPTION This is a re-written MSDN Sample .NOTES File Name : throw-exception.ps1 Author : Thomas Lee - tfl@psp.co.uk Requires : PowerShell V2 CTP3 .LINK Original script at: http://pshscripts.blogspot.com/2009/01/throw-exceptionps1.html MSDN Sample at: http://msdn.microsoft.com/en-us/library/1ah5wsex.aspx .EXAMPLE PS C:\foo> .\Throw-Exception.ps1 Num[0] - Result = 300 Trying to get Num[4] In catch block Error caught: System.IndexOutOfRangeException #> ### # Start of script ### # Helper function function GetNumber{ param ($index) $nums = 300, 600, 900 if ($index -gt $nums.Length) { Throw [system.IndexOutOfRangeException] } else { $nums[$index] } } # Start of main script # Get one that works... $result = GetNumber 0 "Num[0] - Result = {0}" -f $result # Now try and catch the following try { "Trying to get Num[4]" $result = GetNumber 4 } Catch { "In catch block" "Error caught: {0}" -f $Error[0] }
When using throw in a Try-Catch scenario:throw;will re-throw the caught exception, stack trace intact.throw new IndexOutOfRangeException();will generate a new exception (with a new stack trace) and throw that instead.