mcharo
October 18, 2015, 2:50am
1
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
mcharo
October 18, 2015, 3:32am
2
After further research it looks like throw ing 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.
system
October 18, 2015, 4:05am
3
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"
}
nohwnd
October 18, 2015, 6:01am
4
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
mcharo
October 18, 2015, 6:30am
5
Ah of course. Creating the object with that type makes sense. Thanks for the help!