Try to Catch Error Exception Types

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
catch [System.Net.WebException],[System.IO.IOException] {
    "Unable to download MyDoc.doc from
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.



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 (1)

  1. Thanks! I was looking for that since a while… 🙂

Skip to main content