about_Throw

간단한 설명

throw 종료 오류를 생성하는 키워드(keyword) 설명합니다.

자세한 설명

throw 키워드(keyword) 종료 오류가 발생합니다. 키워드(keyword) 사용하여 throw 명령, 함수 또는 스크립트의 처리를 중지할 수 있습니다.

예를 들어 문의 스크립트 블록에서 키워드(keyword) 사용하여 throw 조건에 응답하거나 문 블록에 catch 응답할 수 있습니다try--catchfinally.if

throw 키워드(keyword) 사용자 메시지 문자열 또는 오류를 발생시킨 개체와 같은 모든 개체를 throw할 수 있습니다.

구문

키워드(keyword) 구문 throw 은 다음과 같습니다.

throw [<expression>]

구문의 throw 식은 선택 사항입니다. throw 문이 블록에 catch 나타나지 않고 식을 포함하지 않으면 ScriptHalted 오류가 생성됩니다.

throw
Exception: ScriptHalted

throw 키워드(keyword) 식이 없는 블록에서 catch 사용되는 경우 현재 RuntimeException을 다시 throw합니다. 자세한 내용은 about_Try_Catch_Finally 참조하세요.

문자열 throw

다음 예제와 throw 같이 문의 선택적 식은 문자열일 수 있습니다.

throw "This is an error."
Exception: This is an error.

다른 개체 throw

식은 다음 예제와 같이 PowerShell 프로세스를 나타내는 개체를 throw하는 개체일 수도 있습니다.

throw (Get-Process pwsh)
Exception: System.Diagnostics.Process (pwsh) System.Diagnostics.Process (pwsh) System.Diagnostics.Process (pwsh)

자동 변수에서 ErrorRecord 개체 $ErrorTargetObject 속성을 사용하여 오류를 검사할 수 있습니다.

$Error[0].TargetObject
 NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
 ------    -----      -----     ------      --  -- -----------
    125   174.44     229.57      23.61    1548   2 pwsh
     63    44.07      81.95       1.75    1732   2 pwsh
     63    43.32      77.65       1.48    9092   2 pwsh

ErrorRecord 개체 또는 .NET 예외도 throw가능합니다. 다음 예제에서는 키워드(keyword) 사용하여 throw System.FormatException 개체를 throw합니다.

$formatError = New-Object System.FormatException
throw $formatError
OperationStopped: One of the identified items was in an invalid format.

결과 오류

throw 키워드(keyword) ErrorRecord 개체를 생성할 수 있습니다. ErrorRecord 개체의 Exception 속성에는 RuntimeException 개체가 포함됩니다. ErrorRecord 개체 및 RuntimeException 개체의 re기본der는 throw된 개체에 따라 다릅니다.

개체가 throw ErrorRecord 개체에 래핑되고 ErrorRecord 개체가 자동 변수에 $Error 자동으로 저장됩니다.

필수 매개 변수를 만드는 데 사용 throw

이전 버전의 PowerShell과 달리 매개 변수 유효성 검사에 throw 키워드(keyword) 사용하지 마세요. 올바른 방법은 about_Functions_Advanced_Parameters 참조하세요.

참고 항목