When should I use Write-Error vs. Throw? Terminating vs. non-terminating errors

前端 未结 6 1678
别跟我提以往
别跟我提以往 2020-11-28 03:55

Looking at a Get-WebFile script over on PoshCode, http://poshcode.org/3226, I noticed this strange-to-me contraption:

$URL_Format_Error = [string]\"...\"
Wri         


        
6条回答
  •  鱼传尺愫
    2020-11-28 04:16

    The main difference between the Write-Error cmdlet and the throw keyword in PowerShell is that the former simply prints some text to the standard error stream (stderr), while the latter actually terminates the processing of the running command or function, which is then handled by PowerShell by sending out information about the error to the console.

    You can observe the different behavior of the two in the examples you provided:

    $URL_Format_Error = [string]"..."
    Write-Error $URL_Format_Error
    return
    

    In this example the return keyword has been added to explicitly stop the execution of the script after the error message has been sent out to the console. In the second example, on the other hand, the return keyword is not necessary since termination is implicitly done by throw:

    $URL_Format_Error = New-Object System.FormatException "..."
    Throw $URL_Format_Error
    

提交回复
热议问题