Monday, May 4, 2015

#65 : Error-Handling with Trap

In v1.0 of Windows Powershell, there was no Try-Catch-Finally feature. We had trap construct for the same purpose. I think, Trap was a new concept as it was not there in any of the existing .NET-based languages. But Powershell v1.0 somehow had this unusual feature. In most of the old machines, there will be Powershell v1.0 and we cannot use Try-Catch blocks for those servers. So if you are writing script for all versions of Windows, there is no option left except using Trap.

Let us see the Trap example below :



The above example will call two divide statement which will end up with divide-by-zero. There are two blocks where trap is declared :
1. At script level
2. At function level

You will notice that output will call Function level when it will fail inside function block and it will call script level trap when called outside function.

Hope this simple example will make you learn this correctly. Please send me your questions and suggestion if you have any. Learning from small example is always better if you want to understand something correctly.

That's it for today! Thanks for reading today and keep reading this blog which is updated everyday.


No comments:

Post a Comment

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...