Advanced Error Handling: Rethrowing Exceptions

by Nov 29, 2016

When you handle errors, you may sometimes want to replace the original exception with your own. Here is a sample:

function Do-Something
{
  # function uses internal error handling
  try
  {
    Get-Process -Name NotThereOhWell -ErrorAction Stop
  }
  # catch this error type
  catch [Microsoft.PowerShell.Commands.ProcessCommandException]
  {
    $oldE = $_.Exception

    # handle the error, OR SHOWN HERE: issue a new exception to the caller
    $newE = New-Object -TypeName System.InvalidOperationException('Do-Something: A fatal error occured', $oldE)
    Throw $newE   
  }
}

# function will encounter an internal error
# error message shows error message generated by function instead
Do-Something

This is what the caller sees:

 
PS C:\>  Do-Something
Do-Something: A fatal  error occured
At line:18 char:5
+     Throw $newException
+     ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [],  InvalidOperationException
    +  FullyQualifiedErrorId : Do-Something: A fatal error occured
 

If the caller used an error handler, too, this is what would happen:

try
{
  Do-Something
}
catch [System.InvalidOperationException]
{
  [PSCustomObject]@{
    Message = $_.Exception.Message
    Originalmessage = $_.Exception.InnerException.Message
    }
}

The result would look like this:

 
Message                             Originalmessage                              
-------                             ---------------                              
Do-Something: A fatal error occured Cannot find a process with the name          
                                    "NotThereOhWell". Verify the process name    
                                    and call the cmdlet again.   
 

So the caller can see the error message returned, plus also the original error message received by Do-Something internally.

Twitter This Tip! ReTweet this Tip!