Error handling is a critical aspect of writing robust scripts in any programming language. PowerShell provides a powerful structure for handling errors gracefully using try, catch, and finally blocks. These constructs allows us to manage exceptions and ensure that important cleanup actions are performed, even when errors occur. In this blog post, I will show you how to use try catch finally in PowerShell. Let’s jump in.
Understanding Try, Catch, and Finally
The try block contains the code that may produce an error. If an error occurs, the catch block is executed, allowing you to handle the error. The finally block is optional and contains code that runs regardless of whether an error occurred or not.
Let’s take a look at the syntax.
try {
# Code that might throw an exception
} catch {
# Code to handle the error
} finally {
# Code that runs regardless of whether an error occurred
}
Here are two more examples you can build on.
Try {
1/0
}
Catch {
$_.Exception # Error Message
}
In this example, the error message will be displayed if an error occurs. You might know the $_ variable as a pipeline variable.
And here another example which is more practically and it is a real world scenario.
$ErrorActionPreference="Stop"
Try {
Get-ChildItem -Path C:\notthere
}
Catch {
Write-Warning "Folder not present."
}
You may now ask why I used the $ErrorActionPreference variable. Try it out without changing error handling! I will not work!
In this example, setting ErrorActionPreference to Stop ensures that the Get-ChildItem command’s non-terminating error is caught by the catch block, allowing for appropriate error handling. The error will not be a terminating error, it is in fact a non terminating error, causing PowerShell to ignore the Catch block.
With try-catch blocks, you should therefore always bear in mind that the error could be a non-terminating error that ignores your catch function.
Categories: PowerShell




1 reply »