간단한 설명
종료 오류를 생성하는 throw 키워드에 대해 설명합니다.
긴 설명
throw 키워드로 인해 종료 오류가 발생합니다.
throw 키워드를 사용하여 명령, 함수 또는 스크립트의 처리를 중지할 수 있습니다.
예를 들어 throw 문의 스크립트 블록에서 if 키워드를 사용하여 조건에 응답하거나 catchtry-catch- 문의 finally 블록에 응답할 수 있습니다.
throw 키워드는 사용자 메시지 문자열이나 오류를 일으킨 객체와 같은 모든 객체를 던질 수 있습니다.
문법
throw 키워드의 구문은 다음과 같습니다.
throw [<expression>]
throw 구문의 식은 선택 사항입니다.
throw 문이 catch 블록에 나타나지 않고 식을 포함하지 않으면 ScriptHalted 오류가 생성됩니다.
throw
Exception: ScriptHalted
throw 키워드가 식 없이 catch 블록에서 사용되는 경우 현재 RuntimeException을 다시 throw합니다. 자세한 내용은 about_Try_Catch_Finally를 참조하세요.
문자열을 던지기
throw 문의 선택적 표현식은 다음 예시에서 볼 수 있듯이 문자열일 수 있습니다.
throw "This is an error."
Exception: This is an error.
다른 물체 던지기
식은 다음 예제와 같이 PowerShell 프로세스를 나타내는 개체를 던지는 개체일 수도 있습니다.
throw (Get-Process pwsh)
Exception: System.Diagnostics.Process (pwsh) System.Diagnostics.Process (pwsh) System.Diagnostics.Process (pwsh)
자동 변수에서 ErrorRecord 개체의 $Error 속성을 사용하여 오류를 검사할 수 있습니다.
$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
throw 개체 또는 .NET 예외를 수도 있습니다. 다음 예제에서는 throw 키워드를 사용하여 System.FormatException 개체를 throw합니다.
$formatError = New-Object System.FormatException
throw $formatError
OperationStopped: One of the identified items was in an invalid format.
결과로 발생한 오류
throw 키워드는 ErrorRecord 개체를 생성할 수 있습니다.
ErrorRecord 개체의 Exception 속성에는 RuntimeException 개체가 포함됩니다.
ErrorRecord 개체의 나머지 부분과 RuntimeException 개체는 throw된 개체에 따라 달라집니다.
throw 개체는 ErrorRecord 개체에 래핑되고 ErrorRecord 개체는 자동으로 $Error 자동 변수에 저장됩니다.
throw 사용하여 필수 매개 변수 만들기
이전 버전의 PowerShell과 달리 매개 변수 유효성 검사에 throw 키워드를 사용하지 마세요. 올바른 방법은 about_Functions_Advanced_Parameters 참조하세요.