Try-Catch-Finally is language construct introduced in Powershell v2.0. It provides option to error handling in an elegant manner. While a faulty code might stop flow of your code, Try-Catch can be used to handle some of the obvious errors. For example, if you are writing to a file and suddenly disk got full, your script will fail miserably and error could be trapped further. The script will proceed further without having finishing pervious operation correctly. In a simple language, we can say that Try-Catch gives option to handle errors during runtime without impacting the desired flow of script.
(There are so many big articles written on this subject, this article is just a jump start. My intention is not re-invent the wheel.)
Below is a simple example using this language construct :
(It will run a divide-by-error operation and cause failure. The error will be forwarded on screen)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#---------------------------------------------------------------------------------------------------- | |
#-- Try catch Demo | |
#---------------------------------------------------------------------------------------------------- | |
cls | |
function divide-numbers([int]$x , [int]$y) | |
{ | |
Try { | |
$z= $x/$y | |
} | |
Catch { | |
echo "Failed with error : $($Error[0].Exception.Message) " | |
echo "Error Occured while dividing $x with $y" | |
} | |
finally { | |
echo $z | |
} | |
} | |
divide-numbers 15 3 | |
divide-numbers 15 0 | |
#---------------------------------------------------------------------------------------------------- |
Enjoy developing Powershell scripts!
No comments:
Post a Comment