about_Trap

업데이트 날짜: 2014년 5월

적용 대상: Windows PowerShell 2.0, Windows PowerShell 3.0, Windows PowerShell 4.0

항목

about_Trap

간단한 설명

종료 오류를 처리하는 키워드를 설명합니다.

자세한 설명

종료 오류는 문의 실행을 중지합니다. Windows PowerShell®이 종료 오류를 처리하지 않으면 Windows PowerShell이 현재 파이프라인에서 함수나 스크립트 실행을 중지합니다. C#과 같은 다른 언어에서는 종료 오류를 예외라고 합니다.

Trap 키워드는 종료 오류가 발생할 때 실행할 문 목록을 지정합니다. Trap 문은 종료 오류를 처리하고 이를 통해 스크립트 또는 함수 실행을 중지하지 않고 계속할 수 있습니다.

구문

Trap 문의 구문은 다음과 같습니다.

          trap [[<error type>]] {<statement list>}

Trap 문에는 종료 오류가 발생할 때 실행할 문 목록이 포함됩니다. Trap 키워드는 선택적으로 오류 형식을 지정할 수 있습니다. 오류 형식에는 대괄호가 필요합니다.

스크립트나 명령에는 여러 Trap 문이 포함될 수 있습니다. Trap 문은 스크립트나 명령의 어디에나 나타날 수 있습니다.

모든 종료 명령 트래핑

스크립트나 명령에서 다른 방법으로 처리되지 않는 종료 오류가 발생하면 Windows PowerShell에서는 오류를 처리하는 Trap 문을 확인합니다. Trap 문이 있으면 Windows PowerShell는 계속해서 Trap 문의 스크립트나 명령을 실행합니다.

다음 예제는 매우 간단한 Trap 문입니다.

          trap {"Error found."}

이 Trap 문은 종료 오류를 트래핑합니다. 다음 예제는 이 Trap 문이 포함된 함수입니다.

          function TrapTest {
              trap {"Error found."}
              nonsenseString
              }

이 함수에는 오류를 가져오는 의미 없는 문자열이 포함됩니다. 이 함수를 실행하면 다음 결과가 반환됩니다.

          C:\PS> TrapTest
          Error found.

다음 예제에는 $_ automatic 변수를 사용하여 오류를 표시하는 Trap 문이 포함됩니다.

          function TrapTest {
              trap {"Error found: $_"}
              nonsenseString
              }

이 버전 함수를 실행하면 다음 결과가 반환됩니다.

          C:\PS> TrapTest
          Error found: The term 'nonsenseString' is not recognized as the name 
          of a cmdlet, function, script file, or operable program. Check the 
          spelling of the name, or if a path was included verify that the path 
          is correct, and then try again.

Trap 문은 더 복잡할 수도 있습니다. Trap 문에는 여러 조건이나 함수 호출이 포함될 수 있습니다. 다른 프로그램을 기록, 테스트 또는 실행할 수도 있습니다.

지정된 종료 오류 트래핑

다음 예제는 CommandNotFoundException 오류 형식을 트래핑하는 Trap 문입니다.

          trap [System.Management.Automation.CommandNotFoundException] 
              {"Command error trapped"}

함수나 스크립트에서 알려진 명령과 일치하지 않는 문자열을 발견하면 이 Trap 문은 "Command error trapped" 문자열을 표시합니다. Trap 문 목록에서 문을 실행한 후 Windows PowerShell는 오류 개체를 오류 스트림에 쓰고 스크립트를 계속합니다.

Windows PowerShell에서는 Microsoft .NET Framework 예외 형식을 사용합니다. 다음 예제에서는 System.Exception 오류 형식을 지정합니다.

          trap [System.Exception] {"An error trapped"}

CommandNotFoundException 오류 형식은 System.Exception 형식에서 상속됩니다. 이 문은 알 수 없는 명령에서 생성된 오류를 트래핑합니다. 기타 오류 형식도 트래핑합니다.

한 스크립트에 Trap 문을 두 개 이상 포함할 수 있습니다. 각 오류는 하나의 Trap 문으로만 트래핑할 수 있습니다. 오류가 발생하고 둘 이상의 Trap 문을 사용할 수 있으면 Windows PowerShell에서는 Trap 문을 오류와 일치하는 가장 구체적인 오류 형식과 함께 사용합니다.

다음 스크립트 예제에는 오류가 있습니다. 스크립트에는 종료 오류를 트래핑하는 일반적인 Trap 문과 CommandNotFoundException 형식을 지정하는 특정 Trap 문이 포함됩니다.

          trap {"Other terminating error trapped" }
          trap [System.Management.Automation.CommandNotFoundException] {"Command error trapped"}
          nonsenseString

이 스크립트를 실행하면 다음 결과가 생성됩니다.

          Command  error trapped
          The term 'nonsenseString' is not recognized as the name of a cmdlet, 
          function, script file, or operable program. Check the spelling of 
          the name, or if a path was included verify that the path is correct,
          and then try again.
          At C:\PS>testScript1.ps1:3 char:19
          +     nonsenseString <<<<

Windows PowerShell은 "nonsenseString"을 cmdlet이나 기타 항목으로 인식하지 않으므로 CommandNotFoundException 오류를 반환합니다. 이 종료 오류는 특정 Trap 문으로 트래핑됩니다.

다음 스크립트 예제에는 다른 오류가 포함된 같은 Trap 문이 있습니다.

          trap {"Other terminating error trapped" }
          trap [System.Management.Automation.CommandNotFoundException] 
              {"Command error trapped"}
          1/$null

이 스크립트를 실행하면 다음 결과가 생성됩니다.

          Other terminating error trapped
          Attempted to divide by zero.
          At C:PS> errorX.ps1:3 char:7
          +     1/ <<<< $null

0으로 나누어도 CommandNotFoundException 오류가 발생하지 않습니다. 대신에 해당 오류는 종료 오류를 트래핑하는 다른 Trap 문을 통해 트래핑됩니다.

오류 및 범위 트래핑

종료 오류가 Trap 문과 같은 범위에서 발생하면 Trap 문을 실행한 후 Windows PowerShell은 오류 뒤의 문에서 계속됩니다. Trap 문이 오류와 다른 범위에 있으면 예외는 Trap 문과 같은 범위에 있는 다음 문에서 계속됩니다.

예를 들어 오류가 함수에서 발생하고 Trap 문이 함수에 있으면 스크립트가 다음 문에서 계속됩니다. 예를 들어 다음 스크립트에는 오류 및 Trap 문이 있습니다.

          function function1 {
              trap { "An error: " }
              NonsenseString
              "function1 was completed"
              }

스크립트에서 나중에 Function1 함수를 실행하면 다음 결과가 생성됩니다.

          function1
          An error: 
          The term 'NonsenseString' is not recognized as the name of a cmdlet, 
          function, script file, or operable program. Check the spelling of the 
          name, or if a path was included verify that the path is correct, and 
          then try again.
          At C:\PS>TestScript1.ps1:3 char:19
          +     NonsenseString <<<<

          function1 was completed

함수의 Trap 문이 오류를 트래핑합니다. 메시지를 표시한 후 Windows PowerShell에서는 함수 실행을 다시 시작합니다. Function1이 완료되었는지 확인합니다.

이 예제를 같은 오류 및 Trap 문이 포함된 다음 예제와 비교합니다. 이 예제에서 Trap 문은 함수 외부에서 발생합니다.

          function function2 {
              NonsenseString
              "function2 was completed"
              }

          trap { "An error: " }
              . . .
          function2

스크립트에서 나중에 Function2 함수를 실행하면 다음 결과가 생성됩니다.

          An error: 
          The term 'NonsenseString' is not recognized as the name of a cmdlet, 
          function, script file, or operable program. Check the spelling of the 
          name, or if a path was included verify that the path is correct, and 
          then try again.
          At C:\PS>TestScript2.ps1:4 char:19
          +     NonsenseString <<<<

이 예제에서는 "function2 was completed" 명령이 실행되지 않았습니다. 두 종료 오류가 모두 함수 내에서 발생하지만 Trap 문이 함수 외부에 있으면 Trap 문이 실행된 후 Windows PowerShell이 함수로 돌아가지 않습니다.

BREAK 및 CONTINUE 키워드 사용

Trap 문에서 Break 및 Continue 키워드를 사용하여 종료 오류 후에 스크립트나 명령을 계속 실행할지를 결정합니다.

Trap 문 목록에 Break 문을 포함하면 Windows PowerShell이 함수나 스크립트를 중지합니다. 다음 샘플 함수는 Trap 문에서 Break 키워드를 사용합니다.

          C:\PS> function break_example {
              trap {"Error trapped"; break;}
              1/$null
              "Function completed."
              }

          C:\PS> break_example
          Error trapped
          Attempted to divide by zero.
          At line:4 char:7

Trap 문에 Break 키워드가 포함되었으므로 함수는 계속 실행되지 않고 "Function completed" 줄이 실행되지 않습니다.

Trap 문에 Continue 문을 포함하면 Windows PowerShell은 Break 또는 Continue가 없는 것처럼 오류를 가져온 문 뒤에서 다시 시작됩니다. 그러나 Continue 키워드를 사용하면 Windows PowerShell은 오류를 오류 스트림에 쓰지 않습니다.

다음 샘플 함수는 Trap 문에서 Continue 키워드를 사용합니다.

          C:\PS> function continue_example {
              trap {"Error trapped"; continue;}
              1/$null
              "Function completed."}

          C:\PS> continue_example
          Error trapped
          Function completed.

함수는 오류가 트래핑된 후에 다시 시작되고 "Function completed" 문이 실행됩니다. 오류가 오류 스트림에 기록되지 않습니다.

참고 항목

about_Break

about_Continue

about_Scopes

about_Throw

about_Try_Catch_Finally