Thursday, 22 January 2009

Throw-Exception.ps1

  1. <# 
  2. .SYNOPSIS 
  3.    Shows throwing an exception in a function, caught in caller.   
  4. .DESCRIPTION 
  5.     This is a re-written MSDN Sample 
  6. .NOTES 
  7.     File Name  : throw-exception.ps1 
  8.     Author     : Thomas Lee - tfl@psp.co.uk 
  9.     Requires   : PowerShell V2 CTP3 
  10. .LINK 
  11.     Original script at: 
  12.     http://pshscripts.blogspot.com/2009/01/throw-exceptionps1.html
  13.     MSDN Sample at: 
  14.     http://msdn.microsoft.com/en-us/library/1ah5wsex.aspx  
  15. .EXAMPLE 
  16.     PS C:\foo> .\Throw-Exception.ps1 
  17.     Num[0] - Result = 300 
  18.     Trying to get Num[4] 
  19.     In catch block 
  20.     Error caught: System.IndexOutOfRangeException 
  21. #> 
  22.  
  23. ### 
  24. #  Start of script 
  25. ### 
  26.  
  27.  
  28. # Helper function 
  29. function GetNumber{ 
  30.  param ($index
  31.  $nums = 300, 600, 900 
  32.  if ($index -gt $nums.Length) { 
  33. Throw [system.IndexOutOfRangeException] 
  34.  else
  35.  $nums[$index
  36.  
  37. # Start of main script 
  38.  
  39. # Get one that works... 
  40. $result = GetNumber 0 
  41. "Num[0] - Result = {0}" -f $result 
  42.  
  43. # Now try and catch the following 
  44. try { 
  45. "Trying to get Num[4]" 
  46. $result = GetNumber 4 
  47. Catch { 
  48. "In catch block" 
  49. "Error caught: {0}" -f $Error[0] 

No comments: