Try Catch and Finally
When we need to watch a block of our code for errors, our new best friend is the
try statement. Ever dillagent,
try knows the danger that looms and is looking out for you when a “terminating” error occurs.
We can also tell
try to be on the lookout for other types of errors, those errrors that don’t stop the function in its tracks (also known as Non-Terminating), but may cause problems later in our code because this function was unable to be successfully executed.
An example of a Non-Terminating error would be
Remove-Item not being able to find the object, or
Get-AdUser not being able to find the user in Active Directory. The error thrown by these issues won’t stop the show, it will flood our pretty terminal with a river of red text, but the execution of code will march ever forward.
To instuct our good friend
try to grab Non-Terminating errors we need to use the -ErrorAction property and set it to ‘Stop’ now this Non-Terminating error will behave in a similar manner as a Terminating error (although it is still a Non-Terminating error) and
try will once again do it’s job.
When capturing an error and specifying an error in a catch, it only works with Terminating errors. Non-terminating errors cannot be caught in this manner.
ErrorAction is a different beast than
$ErrorActionPreference is a Preference Variable About Preference Variables This preference variable enable you to customize the behavior and how it affects the PowerShell operating environment and all commands run in the environment.
ErrorAction is a Common Parameter About CommonParameters This common parameter affects the behavior of the specific cmdlet it is used with, and the environment itself is left unchanged. It is used to override the preference for a single command.
ErrorAction has the same valid values as the $ErrorActionPreference variable.
Valid values for $ErrorActionPreference and ErrorAction - Stop: Displays the error message and stops executing. - Inquire: Displays the error message and asks you whether you want to continue. - Continue: Displays the error message and continues (Default) executing. - Suspend: Automatically suspends a workflow job to allow for further investigation. After investigation, the workflow can be resumed. - SilentlyContinue: No effect. The error message is not displayed and execution continues without interruption.
What do you do when ErrorAction parameter isn’t available (it happens in rare cases)? Well customize the $ErrorActionPreference of course!
Hey man… what was that finally thing in that example above? “Finally” executes regardless of the try being successful or not, so it is the perfect place to do some cleaning up.
- Why you would need to use Throw?
- Using the Throw keyword says that the error being thrown is a terminating error?