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. } 
  35.  else { 
  36.  $nums[$index] 
  37. } 
  38. } 
  39.  
  40. # Start of main script 
  41.  
  42. # Get one that works... 
  43. $result = GetNumber 0 
  44. "Num[0] - Result = {0}" -f $result 
  45.  
  46. # Now try and catch the following 
  47. try { 
  48. "Trying to get Num[4]" 
  49. $result = GetNumber 4 
  50. } 
  51. Catch { 
  52. "In catch block" 
  53. "Error caught: {0}" -f $Error[0] 
  54. } 

No comments: