Author Posts

October 18, 2015 at 8:20 am

I'm trying to figure out why this test is falling to the generic catch rather than the specific exception catch:

try
{
    throw [System.Net.WebException]
}
catch [System.Net.WebException]
{
    Write-Host "Caught Web Exception"
}
catch
{
    Write-Host "Caught Exception"
}

Output is:

Caught Exception


> $PSVersionTable.PSVersion.Major
3

October 18, 2015 at 9:02 am

After further research it looks like throwing an exception always results in an exception type of System.Management.Automation.RuntimeException. Generating an actual WebException using Invoke-WebRequest seems to work as expected.

October 18, 2015 at 9:35 am

You would need to actually create an object of that type:

try
{
    throw New-Object -TypeName System.Net.WebException
}
catch [System.Net.WebException]
{
    Write-Host "Caught Web Exception"
}
catch
{
    Write-Host "Caught Exception"
}

October 18, 2015 at 11:31 am

Alternative approach would be to cast a string to the exception type to create a new exception like this:

try {
    throw [Net.WebException]"Exception message"
}
catch [Net.WebException] {
    "Caught Web Exception"
    $_.Exception.Message #or simply "$_"
}
catch {
    "Caught Exception"
}

You can then use the $_ inside the catch block to access the current ErrorRecord and ultimately the message of the exception.

And btw: you don't need the Write-Host in this case 🙂

October 18, 2015 at 12:00 pm

Ah of course. Creating the object with that type makes sense. Thanks for the help!