PowerShell – Exception handling

PowerShell provides exception handling mechanism to enable to deal with the exceptions raised during the script execution. Known or expected errors, we commonly handle using Error handling mechanism; where mostly we use if statement to meet certain criteria and the change the flow of execution depends on the result of the conditional statement.

Exceptional handling mechanism works beyond the Error handling mechanism; where it can able to handle unexpected or unknown errors. Through this article we will learn on the usage of Exception handling mechanism in PowerShell.

Handle Exceptions

In order to use Exceptions handling mechanism in our PowerShell scripts, we need to use Try/Catch blocks along with Throw statements. If the script inside Try block, throws an exceptions will be handled in Catch block; and also we can Throw the exception if something happen unusual.

Let’s take a simple example to handle an Exception; commonly known Exception is Divide by 0. When we directly use the statement to cause this exception, without using Try/Catch blocks, it will throw the Exception and our script terminates.

PS C:\> 1/0
Attempted to divide by zero.
At line:1 char:1
+ 1/0
+ ~~~
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException

If we place the code in Try/Catch block and handle the Exception, the script will not terminate; and will continue to execute the next statements.

PS C:\> Try { 1/0 } Catch { "Divide by 0!" } "Hello!"
Divide by 0!
Hello!

Throw an Exception

By using Throw statement we can throw an exception; and this can be caught in Catch block.

PS C:\> Try { Throw "An Exception." } Catch { $_.ToString() }

[..] David

Add a Comment

Your email address will not be published.