IT

새로운 예외 생성 및 발생

itgroup 2023. 4. 8. 08:23
반응형

새로운 예외 생성 및 발생

PowerShell에서 새로운 예외를 생성하고 생성하는 방법은 무엇입니까?

특정 오류에 대해 다른 작업을 수행합니다.

FileNotFoundException 등의 특정 예외를 호출하려면 다음 형식을 사용합니다.

if (-not (Test-Path $file)) 
{
    throw [System.IO.FileNotFoundException] "$file not found."
}

일반적인 예외를 슬로우하려면 throw 명령 뒤에 문자열을 사용합니다.

throw "Error trying to do a task"

캐치 내에서 사용되는 경우 오류를 트리거한 원인에 대한 추가 정보를 제공할 수 있습니다.

예외 클래스를 확장하여 사용자 지정 오류를 발생시킬 수 있습니다.

class CustomException : Exception {
    [string] $additionalData

    CustomException($Message, $additionalData) : base($Message) {
        $this.additionalData = $additionalData
    }
}

try {
    throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
    # NOTE: To access your custom exception you must use $_.Exception
    Write-Output $_.Exception.additionalData

    # This will produce the error message: Didn't catch it the second time
    throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}

언급URL : https://stackoverflow.com/questions/11981208/creating-and-throwing-new-exception

반응형