Quantcast
Channel: PowerShell.org » All Posts
Viewing all articles
Browse latest Browse all 13067

Reply To: Try/Catch and ErrorAction

$
0
0

Try/Catch will only intercept Terminating errors. Most errors from cmdlets are Non-Terminating, so if you want to handle them with Try/Catch, you need to set ErrorAction (or $ErrorActionPreference) to Stop to force them to become terminating instead.

Converting non-terminating errors into terminating errors may not always be desirable, though; this causes your entire pipeline to abort on the first error, instead of continuing to process other input objects. In those situations, try/catch won’t help you (except to handle a terminating error if one occurs), so you need to use $error or -ErrorVariable instead.

In general, I just stick -ErrorAction Stop onto any command that I’m placing into a Try/Catch block, just in case. Even if you know you don’t need it, it doesn’t hurt anything, and makes the intent clear to anyone who’s reading the code.


Viewing all articles
Browse latest Browse all 13067

Trending Articles