Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
When error handling with Try, Catch, Finally you can create conditional catch statements to target specific exceptions. Here's an example.
try {
$wc = new-object System.Net.WebClient
$wc.DownloadFile("https://www.contoso.com/MyDoc.doc")
}
catch [System.Net.WebException],[System.IO.IOException] {
"Unable to download MyDoc.doc from https://www.contoso.com.
}
catch {
"An error occurred that could not be resolved."
}
Look at the first Catch statement, it's looking for two specific exceptions - [System.Net.WebException] , [System.IO.IOException] . Referencing these exceptions can be a bit 'chicken and egg' though, i.e. how do you know what specific exception type to put into the catch statement? Here's how.
Generate the desired error - that'll be the egg... then use this little statement to get the exception type - the chicken.
$error[0].exception.gettype().fullname
This can then be used in conjunction with a Catch statement to catch a particular exception. For example.
try {...}
catch [System.Management.Automation.MethodException] {"Overload exception"}
catch {"Generic error"}
Comments
- Anonymous
February 28, 2017
Thanks! I was looking for that since a while... :-)