Rethrowing errors

An error might be rethrown within a catch block. This technique can be useful if a try block performs a number of dependent steps in a sequence where one or more might fail.

Rethrowing an error raised by a script can be as simple as using throw in a catch block:

try { 
    'Statement1' 
    throw 'Statement2' 
    'Statement3' 
} catch { 
    throw 
} 

ThrowTerminatingError might be used instead, depending on the desired behavior:

Function Invoke-Something { 
   [CmdletBinding()] 
   Param ( ) 
try { 
    'Statement1' 
    throw 'Statement2' 
    'Statement3' 
} catch { 
    $pscmdlet.ThrowTerminatingError($_) 
} 
} 

When an error is rethrown in this manner, the second instance of the error (within the catch block) is not written to either Error or an error variable. In cases where the error is re-thrown without modification, this does not present a problem.

If the re-thrown error attempts to add information, such as an error ID, the modified error record will also not be available to the error variables. For example:

try { 
    throw 'Error' 
} catch { 
    Write-Error -Exception $_.Exception -ErrorId 'GeneratedErrorId' -Category 'InvalidOperation' 
} 

The error raised in the try block is added to the error variables, but not displayed in a console (as it is handled). The second error is displayed on the console, but not added to any error variables.

To resolve this problem, the new error record should return the original exception as an inner exception:

try { 
    throw 'Error' 
} catch {        
    $exception = New-Object Exception( 
        $_.Exception.Message, 
        $_.Exception 
    ) 
    Write-Error -Exception $exception -ErrorId 'GeneratedErrorId' -Category 'InvalidOperation' 
} 

In the case of exception and most, if not all, exception types, the first argument of the constructor is a message, and the second (optional) argument is an inner exception.

Using an inner exception has a number of advantages:

  • try-catch statements testing the outcome of the preceding snippet will trigger based on either the exception type or inner exception type
  • The other properties of the exception remain available (via the inner exception), such as the stack trace
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.152.136