Try/Catch confusion

This topic contains 4 replies, has 3 voices, and was last updated by  mcharo 1 year, 11 months ago.

  • Author
    Posts
  • #30975

    mcharo
    Participant

    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

  • #30976

    mcharo
    Participant

    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.

  • #30978

    Dave Wyatt
    Moderator

    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"
    }
    
  • #30992

    nohandle
    Member

    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 🙂

  • #30993

    mcharo
    Participant

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

You must be logged in to reply to this topic.