diff --git a/reference/5.1/Microsoft.PowerShell.Core/About/about_Trap.md b/reference/5.1/Microsoft.PowerShell.Core/About/about_Trap.md index 2d7e69639d2c..187b3fe4e6a8 100644 --- a/reference/5.1/Microsoft.PowerShell.Core/About/about_Trap.md +++ b/reference/5.1/Microsoft.PowerShell.Core/About/about_Trap.md @@ -1,7 +1,7 @@ --- description: Describes a keyword that handles a terminating error. Locale: en-US -ms.date: 05/26/2022 +ms.date: 01/17/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_trap?view=powershell-5.1&WT.mc_id=ps-gethelp schema: 2.0.0 title: about Trap @@ -14,7 +14,7 @@ Describes a keyword that handles a terminating error. ## Long description -A terminating error stops a statement from running. If PowerShell does not +A terminating error stops a statement from running. If PowerShell doesn't handle a terminating error in some way, PowerShell also stops running the function or script in the current pipeline. In other languages, such as C#, terminating errors are known as exceptions. @@ -24,8 +24,8 @@ error occurs. `trap` statements can handle the terminating errors in the following ways: - Display the error after processing the `trap` statement block and continuing - execution of the script or function containing the `trap`. This is the - default behavior. + execution of the script or function containing the `trap`. This behavior is + the default. > [!NOTE] > When the terminating error occurs in a subordinate script block, such as @@ -61,15 +61,15 @@ appear anywhere in the script or command. ### Trapping all terminating errors -When a terminating error occurs that is not handled in another way in a script +When a terminating error occurs that isn't handled in another way in a script or command, PowerShell checks for a `trap` statement that handles the error. If a `trap` statement is present, PowerShell continues running the script or command in the `trap` statement. -The following example is a very simple `trap` statement: +The following example is a minimal `trap` statement: ```powershell -trap {"Error found."} +trap { 'Error found.' } ``` This `trap` statement traps any terminating error. @@ -79,23 +79,26 @@ a runtime error. ```powershell function TrapTest { - trap {"Error found."} + trap { 'Error found.' } nonsenseString } TrapTest ``` -Running this function returns the following: +Running this function returns the following output: ```Output Error found. -nonsenseString : 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 try again. +nonsenseString : 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 try again. At line:3 char:5 + nonsenseString + ~~~~~~~~~~~~~~ - + CategoryInfo : ObjectNotFound: (nonsenseString:String) [], CommandNotFoundException + + CategoryInfo : ObjectNotFound: (nonsenseString:String) [] + , CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException ``` @@ -104,23 +107,29 @@ using the `$_` automatic variable: ```powershell function TrapTest { - trap {"Error found: $_"} + trap { "Error found: $_" } nonsenseString } TrapTest ``` -Running this version of the function returns the following: +Running this version of the function returns the following output: ```Output -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 try again. -nonsenseString : 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 try again. +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 +try again. +nonsenseString : 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 try again. At line:3 char:5 + nonsenseString + ~~~~~~~~~~~~~~ - + CategoryInfo : ObjectNotFound: (nonsenseString:String) [], CommandNotFoundException + + CategoryInfo : ObjectNotFound: (nonsenseString:String) [] + , CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException ``` @@ -131,7 +140,7 @@ At line:3 char:5 > In JavaScript, this is known as > [hoisting](https://wikipedia.org/wiki/JavaScript_syntax#hoisting). This means > that `trap` statements apply to all statements in that block even if -> execution has not advanced past the point at which they are defined. For +> execution hasn't advanced past the point at which they're defined. For > example, defining a `trap` at the end of a script and throwing an error in > the first statement still triggers that `trap`. @@ -144,12 +153,13 @@ The following example is a `trap` statement that traps the specific error **CommandNotFoundException**: ```powershell -trap [System.Management.Automation.CommandNotFoundException] - {"Command error trapped"} +trap [System.Management.Automation.CommandNotFoundException] { + 'Command error trapped' +} ``` -When a function or script encounters a string that does not match a known -command, this `trap` statement displays the "Command error trapped" string. +When a function or script encounters a string that doesn't match a known +command, this `trap` statement displays the `Command error trapped` string. After running the `trap` statement list, PowerShell writes the error object to the error stream and then continues the script. @@ -157,26 +167,50 @@ PowerShell uses .NET exception types. The following example specifies the **System.Exception** error type: ```powershell -trap [System.Exception] {"An error trapped"} +trap [System.Exception] { 'An error trapped' } ``` The **CommandNotFoundException** error type inherits from the -**System.Exception** type. This statement traps an error that is created by an -unknown command. It also traps other error types. +**System.Exception** type. This statement traps any errors raised by unknown +commands. It also traps other error types. -You can have more than one `trap` statement in a script. Each error type can be -trapped by only one `trap` statement. When a terminating error occurs, -PowerShell searches for the `trap` with the most specific match, starting in -the current script block of execution. +You can find the exception type for an error by inspecting the error object. +The following example shows how to get the full name of the exception for the +last error in a session: + +```powershell +nonsenseString +$Error[0].Exception.GetType().FullName +``` + +```Output +nonsenseString : 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 try again. +At line:1 char:1 ++ nonsenseString ++ ~~~~~~~~~~~~~~ + + CategoryInfo : ObjectNotFound: (nonsenseString:String) [] + , CommandNotFoundException + + FullyQualifiedErrorId : CommandNotFoundException + +System.Management.Automation.CommandNotFoundException +``` + +You can have more than one `trap` statement in a script. Only one `trap` +statement can trap each error type. When a terminating error occurs, PowerShell +searches for the `trap` with the most specific match, starting in the current +script block of execution. The following script example contains an error. The script includes a general `trap` statement that traps any terminating error and a specific `trap` statement that specifies the **CommandNotFoundException** type. ```powershell -trap {"Other terminating error trapped" } +trap { 'Other terminating error trapped' } trap [System.Management.Automation.CommandNotFoundException] { - "Command error trapped" + 'Command error trapped' } nonsenseString ``` @@ -185,43 +219,48 @@ Running this script produces the following result: ```Output Command error trapped -nonsenseString : 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 try again. -At C:\Temp\traptest.ps1:5 char:1 -+ nonsenseString +nonsenseString : 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 try again. +At line:5 char:1 ++ nonsenseString} + ~~~~~~~~~~~~~~ - + CategoryInfo : ObjectNotFound: (nonsenseString:String) [], CommandNotFoundException + + CategoryInfo : ObjectNotFound: (nonsenseString:String) [] + , CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException ``` -Because PowerShell does not recognize "nonsenseString" as a cmdlet or other -item, it returns a **CommandNotFoundException** error. This terminating error -is trapped by the specific `trap` statement. +Because PowerShell doesn't recognize "nonsenseString" as a cmdlet or other +item, it returns a **CommandNotFoundException** error. The specific `trap` +statement traps this terminating error. The following script example contains the same `trap` statements with a different error: ```powershell -trap {"Other terminating error trapped" } -trap [System.Management.Automation.CommandNotFoundException] - {"Command error trapped"} +trap { 'Other terminating error trapped' } +trap [System.Management.Automation.CommandNotFoundException] { + 'Command error trapped' +} 1/$null ``` Running this script produces the following result: ```Output +Other terminating error trapped Attempted to divide by zero. -At C:\temp\traptest.ps1:4 char:1 -+ 1/$null +At line:5 char:1 ++ 1/$null} + ~~~~~~~ + CategoryInfo : NotSpecified: (:) [], RuntimeException + FullyQualifiedErrorId : RuntimeException ``` -The attempt to divide by zero does not create a **CommandNotFoundException** -error. Instead, that error is trapped by the other `trap` statement, which traps -any terminating error. +The attempt to divide by zero doesn't create a **CommandNotFoundException** +error. The other `trap` statement, which traps any terminating error, traps the +divide by zero error. ### Trapping errors in a script block @@ -229,9 +268,9 @@ By default, when a terminating error is thrown, execution transfers to the trap statement. After the `trap` block is run, control returns to the next statement block after the location of the error. -For example, when a terminating error occurs in an `foreach` statement, the `trap` -statement is run and execution continues at the next statement after the `foreach` block, -not within the `foreach` block. +For example, when a terminating error occurs in an `foreach` statement, the +`trap` statement is run and execution continues at the next statement after the +`foreach` block, not within the `foreach` block. ```powershell trap { 'An error occurred!'} @@ -260,10 +299,10 @@ At line:3 char:4 after loop ``` -In the output above, you can see the loops continue until the last iteration. -When the script tries to divide 1 by 0 a terminating error is thrown. The rest -of the `foreach` scriptblock is skipped, the `try` statement is run, and the -script continues after the `foreach` scriptblock. +In the output, you can see the loops continue until the last iteration. When +the script tries to divide 1 by 0, PowerShell throws a terminating error. The +script skips the rest of the `foreach` script block, runs the `try` statement, +and continues after the `foreach` script block. ### Trapping errors and scope @@ -271,7 +310,7 @@ If a terminating error occurs in the same script block as the `trap` statement, PowerShell runs the list of statements defined by the `trap`. Execution continues at the statement after the error. If the `trap` statement is in a different script block from the error, execution continues at the next -statement that is in the same script block as the `trap` statement. +statement that's in the same script block as the `trap` statement. For example, if an error occurs in a function, and the `trap` statement is in the function, the script continues at the next statement. The following script @@ -279,9 +318,9 @@ contains an error and a `trap` statement: ```powershell function function1 { - trap { "An error: " } + trap { 'An error: ' } NonsenseString - "function1 was completed" + 'function1 was completed' } function1 @@ -291,31 +330,35 @@ Running this script produces the following result: ```Output An error: -NonsenseString : 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 try again. +NonsenseString : 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 try again. At line:3 char:5 + NonsenseString + ~~~~~~~~~~~~~~ - + CategoryInfo : ObjectNotFound: (NonsenseString:String) [], CommandNotFoundException + + CategoryInfo : ObjectNotFound: (NonsenseString:String) [] + , CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException function1 was completed ``` The `trap` statement in the function traps the error. After displaying the -message, PowerShell resumes running the function. Note that `Function1` was -completed. +message, PowerShell resumes running the function. Notice that `Function1` +completed after the `trap` statement. -Compare this with the following example, which has the same error and `trap` -statement. In this example, the `trap` statement occurs outside the function: +Compare this behavior with the following example, which has the same error and +`trap` statement. In this example, the `trap` statement occurs outside the +function: ```powershell function function2 { NonsenseString - "function2 was completed" + 'function2 was completed' } -trap { "An error: " } +trap { 'An error:' } function2 ``` @@ -324,36 +367,39 @@ Running the `Function2` function produces the following result: ```Output An error: -NonsenseString : 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 try again. -At C:\temp\traptest.ps1:2 char:5 +NonsenseString : 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 try again. +At line:2 char:5 + NonsenseString + ~~~~~~~~~~~~~~ - + CategoryInfo : ObjectNotFound: (NonsenseString:String) [], CommandNotFoundException + + CategoryInfo : ObjectNotFound: (NonsenseString:String) [] + , CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException ``` -In this example, the "function2 was completed" command was not run. In both +In this example, the `function2 was completed` command wasn't run. In both examples, the terminating error occurs within the function. In this example, -however, the `trap` statement is outside the function. PowerShell does not go +however, the `trap` statement is outside the function. PowerShell doesn't go back into the function after the `trap` statement runs. > [!CAUTION] > When multiple traps are defined for the same error condition, the first `trap` > defined lexically (highest in the script block) is used. -In the following example, only the `trap` with "whoops 1" is run. +In the following example, only the `trap` with `whoops 1` runs. ```powershell Remove-Item -ErrorAction Stop ThisFileDoesNotExist -trap { "whoops 1"; continue } -trap { "whoops 2"; continue } +trap { 'whoops 1'; continue } +trap { 'whoops 2'; continue } ``` > [!IMPORTANT] -> A Trap statement is scoped to where it compiles. If you have a -> `trap` statement inside a function or dot sourced script, when the function -> or dot sourced script exits, all `trap` statements inside are removed. +> A `trap` statement is scoped to where it compiles. If you have a `trap` +> statement inside a function or dot sourced script, when the function or dot +> sourced script exits, all `trap` statements inside are removed. ### Using the break and continue keywords @@ -368,11 +414,11 @@ in a `trap` statement: ```powershell function break_example { trap { - "Error trapped" + 'Error trapped' break } 1/$null - "Function completed." + 'Function completed.' } break_example @@ -384,16 +430,17 @@ Attempted to divide by zero. At line:6 char:5 + 1/$null + ~~~~~~~ - + CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException + + CategoryInfo : NotSpecified: (:) [], ParentContainsErrorR + ecordException + FullyQualifiedErrorId : RuntimeException ``` -Because the `trap` statement included the `break` keyword, the function does -not continue to run, and the "Function completed" line is not run. +Because the `trap` statement included the `break` keyword, the function doesn't +continue to run, and the `Function completed` line isn't run. If you include a `continue` keyword in a `trap` statement, PowerShell resumes after the statement that caused the error, just as it would without `break` or -`continue`. With the `continue` keyword, however, PowerShell does not write an +`continue`. With the `continue` keyword, however, PowerShell doesn't write an error to the error stream. The following sample function uses the `continue` keyword in a `trap` @@ -402,11 +449,11 @@ statement: ```powershell function continue_example { trap { - "Error trapped" + 'Error trapped' continue } 1/$null - "Function completed." + 'Function completed.' } continue_example @@ -417,7 +464,7 @@ Error trapped Function completed. ``` -The function resumes after the error is trapped, and the "Function completed" +The function resumes after the error is trapped, and the `Function completed` statement runs. No error is written to the error stream. ## Notes diff --git a/reference/7.2/Microsoft.PowerShell.Core/About/about_Trap.md b/reference/7.2/Microsoft.PowerShell.Core/About/about_Trap.md index 8710d6227180..935fd4b67f7e 100644 --- a/reference/7.2/Microsoft.PowerShell.Core/About/about_Trap.md +++ b/reference/7.2/Microsoft.PowerShell.Core/About/about_Trap.md @@ -1,7 +1,7 @@ --- description: Describes a keyword that handles a terminating error. Locale: en-US -ms.date: 05/26/2022 +ms.date: 01/17/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_trap?view=powershell-7.2&WT.mc_id=ps-gethelp schema: 2.0.0 title: about Trap @@ -14,7 +14,7 @@ Describes a keyword that handles a terminating error. ## Long description -A terminating error stops a statement from running. If PowerShell does not +A terminating error stops a statement from running. If PowerShell doesn't handle a terminating error in some way, PowerShell also stops running the function or script in the current pipeline. In other languages, such as C#, terminating errors are known as exceptions. @@ -24,8 +24,8 @@ error occurs. `trap` statements can handle the terminating errors in the following ways: - Display the error after processing the `trap` statement block and continuing - execution of the script or function containing the `trap`. This is the - default behavior. + execution of the script or function containing the `trap`. This behavior is + the default. > [!NOTE] > When the terminating error occurs in a subordinate script block, such as @@ -61,15 +61,15 @@ appear anywhere in the script or command. ### Trapping all terminating errors -When a terminating error occurs that is not handled in another way in a script +When a terminating error occurs that isn't handled in another way in a script or command, PowerShell checks for a `trap` statement that handles the error. If a `trap` statement is present, PowerShell continues running the script or command in the `trap` statement. -The following example is a very simple `trap` statement: +The following example is a minimal `trap` statement: ```powershell -trap {"Error found."} +trap { 'Error found.' } ``` This `trap` statement traps any terminating error. @@ -79,14 +79,14 @@ a runtime error. ```powershell function TrapTest { - trap {"Error found."} + trap { 'Error found.' } nonsenseString } TrapTest ``` -Running this function returns the following: +Running this function returns the following output: ```Output Error found. @@ -94,9 +94,10 @@ nonsenseString: Line | 3 | nonsenseString | ~~~~~~~~~~~~~~ - | 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 try again. + | The term 'nonsenseString' is not recognized as a name of a cmdlet, +function, script file, or executable program. +Check the spelling of the name, or if a path was included, verify that the +path is correct and try again. ``` The following example includes a `trap` statement that displays the error by @@ -104,26 +105,28 @@ using the `$_` automatic variable: ```powershell function TrapTest { - trap {"Error found: $_"} + trap { "Error found: $_" } nonsenseString } TrapTest ``` -Running this version of the function returns the following: +Running this version of the function returns the following output: ```Output 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 try again. +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 +try again. nonsenseString: Line | 3 | nonsenseString | ~~~~~~~~~~~~~~ - | 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 try again. + | The term 'nonsenseString' is not recognized as a name of a cmdlet, +function, script file, or executable program. +Check the spelling of the name, or if a path was included, verify that the +path is correct and try again. ``` > [!IMPORTANT] @@ -133,7 +136,7 @@ if a path was included, verify that the path is correct and try again. > In JavaScript, this is known as > [hoisting](https://wikipedia.org/wiki/JavaScript_syntax#hoisting). This means > that `trap` statements apply to all statements in that block even if -> execution has not advanced past the point at which they are defined. For +> execution hasn't advanced past the point at which they're defined. For > example, defining a `trap` at the end of a script and throwing an error in > the first statement still triggers that `trap`. @@ -146,12 +149,13 @@ The following example is a `trap` statement that traps the specific error **CommandNotFoundException**: ```powershell -trap [System.Management.Automation.CommandNotFoundException] - {"Command error trapped"} +trap [System.Management.Automation.CommandNotFoundException] { + 'Command error trapped' +} ``` -When a function or script encounters a string that does not match a known -command, this `trap` statement displays the "Command error trapped" string. +When a function or script encounters a string that doesn't match a known +command, this `trap` statement displays the `Command error trapped` string. After running the `trap` statement list, PowerShell writes the error object to the error stream and then continues the script. @@ -159,26 +163,44 @@ PowerShell uses .NET exception types. The following example specifies the **System.Exception** error type: ```powershell -trap [System.Exception] {"An error trapped"} +trap [System.Exception] { 'An error trapped' } ``` The **CommandNotFoundException** error type inherits from the -**System.Exception** type. This statement traps an error that is created by an -unknown command. It also traps other error types. +**System.Exception** type. This statement traps any errors raised by unknown +commands. It also traps other error types. + +You can find the exception type for an error by inspecting the error object. +The following example shows how to get the full name of the exception for the +last error in a session: + +```powershell +nonsenseString +$Error[0].Exception.GetType().FullName +``` + +```Output +nonsenseString: The term 'nonsenseString' is not recognized as a name of a +cmdlet, function, script file, or executable program. Check the spelling +of the name, or if a path was included, verify that the path is correct +and try again. + +System.Management.Automation.CommandNotFoundException +``` -You can have more than one `trap` statement in a script. Each error type can be -trapped by only one `trap` statement. When a terminating error occurs, -PowerShell searches for the `trap` with the most specific match, starting in -the current script block of execution. +You can have more than one `trap` statement in a script. Only one `trap` +statement can trap each error type. When a terminating error occurs, PowerShell +searches for the `trap` with the most specific match, starting in the current +script block of execution. The following script example contains an error. The script includes a general `trap` statement that traps any terminating error and a specific `trap` statement that specifies the **CommandNotFoundException** type. ```powershell -trap {"Other terminating error trapped" } +trap { 'Other terminating error trapped' } trap [System.Management.Automation.CommandNotFoundException] { - "Command error trapped" + 'Command error trapped' } nonsenseString ``` @@ -189,24 +211,26 @@ Running this script produces the following result: Command error trapped nonsenseString: Line | - 5 | nonsenseString - | ~~~~~~~~~~~~~~ - | 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 try again. + 5 | nonsenseString + | ~~~~~~~~~~~~~~ + | The term 'nonsenseString' is not recognized as a name of a cmdlet, +function, script file, or executable program. +Check the spelling of the name, or if a path was included, verify that the +path is correct and try again. ``` -Because PowerShell does not recognize "nonsenseString" as a cmdlet or other -item, it returns a **CommandNotFoundException** error. This terminating error -is trapped by the specific `trap` statement. +Because PowerShell doesn't recognize `nonsenseString` as a cmdlet or other +item, it returns a **CommandNotFoundException** error. The specific `trap` +statement traps this terminating error. The following script example contains the same `trap` statements with a different error: ```powershell -trap {"Other terminating error trapped" } -trap [System.Management.Automation.CommandNotFoundException] - {"Command error trapped"} +trap { 'Other terminating error trapped' } +trap [System.Management.Automation.CommandNotFoundException] { + 'Command error trapped' +} 1/$null ``` @@ -216,14 +240,14 @@ Running this script produces the following result: Other terminating error trapped RuntimeException: Line | - 4 | 1/$null + 5 | 1/$null | ~~~~~~~ | Attempted to divide by zero. ``` -The attempt to divide by zero does not create a **CommandNotFoundException** -error. Instead, that error is trapped by the other `trap` statement, which traps -any terminating error. +The attempt to divide by zero doesn't create a **CommandNotFoundException** +error. The other `trap` statement, which traps any terminating error, traps the +divide by zero error. ### Trapping errors in a script block @@ -231,9 +255,9 @@ By default, when a terminating error is thrown, execution transfers to the trap statement. After the `trap` block is run, control returns to the next statement block after the location of the error. -For example, when a terminating error occurs in an `foreach` statement, the `trap` -statement is run and execution continues at the next statement after the `foreach` block, -not within the `foreach` block. +For example, when a terminating error occurs in an `foreach` statement, the +`trap` statement is run and execution continues at the next statement after the +`foreach` block, not within the `foreach` block. ```powershell trap { 'An error occurred!'} @@ -252,19 +276,18 @@ after division 1 after division An error occurred! -RuntimeException: untitled:Untitled-1:3:4 +RuntimeException: Line | 3 | 1/$x | ~~~~ | Attempted to divide by zero. - after loop ``` -In the output above, you can see the loops continue until the last iteration. -When the script tries to divide 1 by 0 a terminating error is thrown. The rest -of the `foreach` scriptblock is skipped, the `try` statement is run, and the -script continues after the `foreach` scriptblock. +In the output, you can see the loops continue until the last iteration. When +the script tries to divide 1 by 0, PowerShell throws a terminating error. The +script skips the rest of the `foreach` script block, runs the `try` statement, +and continues after the `foreach` script block. ### Trapping errors and scope @@ -272,7 +295,7 @@ If a terminating error occurs in the same script block as the `trap` statement, PowerShell runs the list of statements defined by the `trap`. Execution continues at the statement after the error. If the `trap` statement is in a different script block from the error, execution continues at the next -statement that is in the same script block as the `trap` statement. +statement that's in the same script block as the `trap` statement. For example, if an error occurs in a function, and the `trap` statement is in the function, the script continues at the next statement. The following script @@ -280,9 +303,9 @@ contains an error and a `trap` statement: ```powershell function function1 { - trap { "An error: " } + trap { 'An error: ' } NonsenseString - "function1 was completed" + 'function1 was completed' } function1 @@ -296,26 +319,28 @@ NonsenseString: Line | 3 | NonsenseString | ~~~~~~~~~~~~~~ - | 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 try again. + | The term 'NonsenseString' is not recognized as a name of a cmdlet, +function, script file, or executable program. +Check the spelling of the name, or if a path was included, verify that the +path is correct and try again. function1 was completed ``` The `trap` statement in the function traps the error. After displaying the -message, PowerShell resumes running the function. Note that `Function1` was -completed. +message, PowerShell resumes running the function. Notice that `Function1` +completed after the `trap` statement. -Compare this with the following example, which has the same error and `trap` -statement. In this example, the `trap` statement occurs outside the function: +Compare this behavior with the following example, which has the same error and +`trap` statement. In this example, the `trap` statement occurs outside the +function: ```powershell function function2 { NonsenseString - "function2 was completed" + 'function2 was completed' } -trap { "An error: " } +trap { 'An error:' } function2 ``` @@ -328,32 +353,33 @@ NonsenseString: Line | 2 | NonsenseString | ~~~~~~~~~~~~~~ - | 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 try again. + | The term 'NonsenseString' is not recognized as a name of a cmdlet, +function, script file, or executable program. +Check the spelling of the name, or if a path was included, verify that the +path is correct and try again. ``` -In this example, the "function2 was completed" command was not run. In both +In this example, the `function2 was completed` command wasn't run. In both examples, the terminating error occurs within the function. In this example, -however, the `trap` statement is outside the function. PowerShell does not go +however, the `trap` statement is outside the function. PowerShell doesn't go back into the function after the `trap` statement runs. > [!CAUTION] > When multiple traps are defined for the same error condition, the first `trap` > defined lexically (highest in the script block) is used. -In the following example, only the `trap` with "whoops 1" is run. +In the following example, only the `trap` with `whoops 1` runs. ```powershell Remove-Item -ErrorAction Stop ThisFileDoesNotExist -trap { "whoops 1"; continue } -trap { "whoops 2"; continue } +trap { 'whoops 1'; continue } +trap { 'whoops 2'; continue } ``` > [!IMPORTANT] -> A Trap statement is scoped to where it compiles. If you have a -> `trap` statement inside a function or dot sourced script, when the function -> or dot sourced script exits, all `trap` statements inside are removed. +> A `trap` statement is scoped to where it compiles. If you have a `trap` +> statement inside a function or dot sourced script, when the function or dot +> sourced script exits, all `trap` statements inside are removed. ### Using the break and continue keywords @@ -368,11 +394,11 @@ in a `trap` statement: ```powershell function break_example { trap { - "Error trapped" + 'Error trapped' break } 1/$null - "Function completed." + 'Function completed.' } break_example @@ -387,12 +413,12 @@ Line | | Attempted to divide by zero. ``` -Because the `trap` statement included the `break` keyword, the function does -not continue to run, and the "Function completed" line is not run. +Because the `trap` statement included the `break` keyword, the function doesn't +continue to run, and the `Function completed` line isn't run. If you include a `continue` keyword in a `trap` statement, PowerShell resumes after the statement that caused the error, just as it would without `break` or -`continue`. With the `continue` keyword, however, PowerShell does not write an +`continue`. With the `continue` keyword, however, PowerShell doesn't write an error to the error stream. The following sample function uses the `continue` keyword in a `trap` @@ -401,11 +427,11 @@ statement: ```powershell function continue_example { trap { - "Error trapped" + 'Error trapped' continue } 1/$null - "Function completed." + 'Function completed.' } continue_example @@ -416,7 +442,7 @@ Error trapped Function completed. ``` -The function resumes after the error is trapped, and the "Function completed" +The function resumes after the error is trapped, and the `Function completed` statement runs. No error is written to the error stream. ## Notes diff --git a/reference/7.3/Microsoft.PowerShell.Core/About/about_Trap.md b/reference/7.3/Microsoft.PowerShell.Core/About/about_Trap.md index f94c471b63d6..bd7731e64354 100644 --- a/reference/7.3/Microsoft.PowerShell.Core/About/about_Trap.md +++ b/reference/7.3/Microsoft.PowerShell.Core/About/about_Trap.md @@ -1,7 +1,7 @@ --- description: Describes a keyword that handles a terminating error. Locale: en-US -ms.date: 05/26/2022 +ms.date: 01/17/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_trap?view=powershell-7.3&WT.mc_id=ps-gethelp schema: 2.0.0 title: about Trap @@ -14,7 +14,7 @@ Describes a keyword that handles a terminating error. ## Long description -A terminating error stops a statement from running. If PowerShell does not +A terminating error stops a statement from running. If PowerShell doesn't handle a terminating error in some way, PowerShell also stops running the function or script in the current pipeline. In other languages, such as C#, terminating errors are known as exceptions. @@ -24,8 +24,8 @@ error occurs. `trap` statements can handle the terminating errors in the following ways: - Display the error after processing the `trap` statement block and continuing - execution of the script or function containing the `trap`. This is the - default behavior. + execution of the script or function containing the `trap`. This behavior is + the default. > [!NOTE] > When the terminating error occurs in a subordinate script block, such as @@ -61,15 +61,15 @@ appear anywhere in the script or command. ### Trapping all terminating errors -When a terminating error occurs that is not handled in another way in a script +When a terminating error occurs that isn't handled in another way in a script or command, PowerShell checks for a `trap` statement that handles the error. If a `trap` statement is present, PowerShell continues running the script or command in the `trap` statement. -The following example is a very simple `trap` statement: +The following example is a minimal `trap` statement: ```powershell -trap {"Error found."} +trap { 'Error found.' } ``` This `trap` statement traps any terminating error. @@ -79,14 +79,14 @@ a runtime error. ```powershell function TrapTest { - trap {"Error found."} + trap { 'Error found.' } nonsenseString } TrapTest ``` -Running this function returns the following: +Running this function returns the following output: ```Output Error found. @@ -94,9 +94,10 @@ nonsenseString: Line | 3 | nonsenseString | ~~~~~~~~~~~~~~ - | 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 try again. + | The term 'nonsenseString' is not recognized as a name of a cmdlet, +function, script file, or executable program. +Check the spelling of the name, or if a path was included, verify that the +path is correct and try again. ``` The following example includes a `trap` statement that displays the error by @@ -104,26 +105,28 @@ using the `$_` automatic variable: ```powershell function TrapTest { - trap {"Error found: $_"} + trap { "Error found: $_" } nonsenseString } TrapTest ``` -Running this version of the function returns the following: +Running this version of the function returns the following output: ```Output 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 try again. +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 +try again. nonsenseString: Line | 3 | nonsenseString | ~~~~~~~~~~~~~~ - | 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 try again. + | The term 'nonsenseString' is not recognized as a name of a cmdlet, +function, script file, or executable program. +Check the spelling of the name, or if a path was included, verify that the +path is correct and try again. ``` > [!IMPORTANT] @@ -133,7 +136,7 @@ if a path was included, verify that the path is correct and try again. > In JavaScript, this is known as > [hoisting](https://wikipedia.org/wiki/JavaScript_syntax#hoisting). This means > that `trap` statements apply to all statements in that block even if -> execution has not advanced past the point at which they are defined. For +> execution hasn't advanced past the point at which they're defined. For > example, defining a `trap` at the end of a script and throwing an error in > the first statement still triggers that `trap`. @@ -146,12 +149,13 @@ The following example is a `trap` statement that traps the specific error **CommandNotFoundException**: ```powershell -trap [System.Management.Automation.CommandNotFoundException] - {"Command error trapped"} +trap [System.Management.Automation.CommandNotFoundException] { + 'Command error trapped' +} ``` -When a function or script encounters a string that does not match a known -command, this `trap` statement displays the "Command error trapped" string. +When a function or script encounters a string that doesn't match a known +command, this `trap` statement displays the `Command error trapped` string. After running the `trap` statement list, PowerShell writes the error object to the error stream and then continues the script. @@ -159,26 +163,44 @@ PowerShell uses .NET exception types. The following example specifies the **System.Exception** error type: ```powershell -trap [System.Exception] {"An error trapped"} +trap [System.Exception] { 'An error trapped' } ``` The **CommandNotFoundException** error type inherits from the -**System.Exception** type. This statement traps an error that is created by an -unknown command. It also traps other error types. +**System.Exception** type. This statement traps any errors raised by unknown +commands. It also traps other error types. + +You can find the exception type for an error by inspecting the error object. +The following example shows how to get the full name of the exception for the +last error in a session: + +```powershell +nonsenseString +$Error[0].Exception.GetType().FullName +``` + +```Output +nonsenseString: The term 'nonsenseString' is not recognized as a name of a +cmdlet, function, script file, or executable program. Check the spelling +of the name, or if a path was included, verify that the path is correct +and try again. + +System.Management.Automation.CommandNotFoundException +``` -You can have more than one `trap` statement in a script. Each error type can be -trapped by only one `trap` statement. When a terminating error occurs, -PowerShell searches for the `trap` with the most specific match, starting in -the current script block of execution. +You can have more than one `trap` statement in a script. Only one `trap` +statement can trap each error type. When a terminating error occurs, PowerShell +searches for the `trap` with the most specific match, starting in the current +script block of execution. The following script example contains an error. The script includes a general `trap` statement that traps any terminating error and a specific `trap` statement that specifies the **CommandNotFoundException** type. ```powershell -trap {"Other terminating error trapped" } +trap { 'Other terminating error trapped' } trap [System.Management.Automation.CommandNotFoundException] { - "Command error trapped" + 'Command error trapped' } nonsenseString ``` @@ -189,24 +211,26 @@ Running this script produces the following result: Command error trapped nonsenseString: Line | - 5 | nonsenseString - | ~~~~~~~~~~~~~~ - | 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 try again. + 5 | nonsenseString + | ~~~~~~~~~~~~~~ + | The term 'nonsenseString' is not recognized as a name of a cmdlet, +function, script file, or executable program. +Check the spelling of the name, or if a path was included, verify that the +path is correct and try again. ``` -Because PowerShell does not recognize "nonsenseString" as a cmdlet or other -item, it returns a **CommandNotFoundException** error. This terminating error -is trapped by the specific `trap` statement. +Because PowerShell doesn't recognize `nonsenseString` as a cmdlet or other +item, it returns a **CommandNotFoundException** error. The specific `trap` +statement traps this terminating error. The following script example contains the same `trap` statements with a different error: ```powershell -trap {"Other terminating error trapped" } -trap [System.Management.Automation.CommandNotFoundException] - {"Command error trapped"} +trap { 'Other terminating error trapped' } +trap [System.Management.Automation.CommandNotFoundException] { + 'Command error trapped' +} 1/$null ``` @@ -216,14 +240,14 @@ Running this script produces the following result: Other terminating error trapped RuntimeException: Line | - 4 | 1/$null + 5 | 1/$null | ~~~~~~~ | Attempted to divide by zero. ``` -The attempt to divide by zero does not create a **CommandNotFoundException** -error. Instead, that error is trapped by the other `trap` statement, which traps -any terminating error. +The attempt to divide by zero doesn't create a **CommandNotFoundException** +error. The other `trap` statement, which traps any terminating error, traps the +divide by zero error. ### Trapping errors in a script block @@ -231,9 +255,9 @@ By default, when a terminating error is thrown, execution transfers to the trap statement. After the `trap` block is run, control returns to the next statement block after the location of the error. -For example, when a terminating error occurs in an `foreach` statement, the `trap` -statement is run and execution continues at the next statement after the `foreach` block, -not within the `foreach` block. +For example, when a terminating error occurs in an `foreach` statement, the +`trap` statement is run and execution continues at the next statement after the +`foreach` block, not within the `foreach` block. ```powershell trap { 'An error occurred!'} @@ -252,19 +276,18 @@ after division 1 after division An error occurred! -RuntimeException: untitled:Untitled-1:3:4 +RuntimeException: Line | 3 | 1/$x | ~~~~ | Attempted to divide by zero. - after loop ``` -In the output above, you can see the loops continue until the last iteration. -When the script tries to divide 1 by 0 a terminating error is thrown. The rest -of the `foreach` scriptblock is skipped, the `try` statement is run, and the -script continues after the `foreach` scriptblock. +In the output, you can see the loops continue until the last iteration. When +the script tries to divide 1 by 0, PowerShell throws a terminating error. The +script skips the rest of the `foreach` script block, runs the `try` statement, +and continues after the `foreach` script block. ### Trapping errors and scope @@ -272,7 +295,7 @@ If a terminating error occurs in the same script block as the `trap` statement, PowerShell runs the list of statements defined by the `trap`. Execution continues at the statement after the error. If the `trap` statement is in a different script block from the error, execution continues at the next -statement that is in the same script block as the `trap` statement. +statement that's in the same script block as the `trap` statement. For example, if an error occurs in a function, and the `trap` statement is in the function, the script continues at the next statement. The following script @@ -280,9 +303,9 @@ contains an error and a `trap` statement: ```powershell function function1 { - trap { "An error: " } + trap { 'An error: ' } NonsenseString - "function1 was completed" + 'function1 was completed' } function1 @@ -296,26 +319,28 @@ NonsenseString: Line | 3 | NonsenseString | ~~~~~~~~~~~~~~ - | 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 try again. + | The term 'NonsenseString' is not recognized as a name of a cmdlet, +function, script file, or executable program. +Check the spelling of the name, or if a path was included, verify that the +path is correct and try again. function1 was completed ``` The `trap` statement in the function traps the error. After displaying the -message, PowerShell resumes running the function. Note that `Function1` was -completed. +message, PowerShell resumes running the function. Notice that `Function1` +completed after the `trap` statement. -Compare this with the following example, which has the same error and `trap` -statement. In this example, the `trap` statement occurs outside the function: +Compare this behavior with the following example, which has the same error and +`trap` statement. In this example, the `trap` statement occurs outside the +function: ```powershell function function2 { NonsenseString - "function2 was completed" + 'function2 was completed' } -trap { "An error: " } +trap { 'An error:' } function2 ``` @@ -328,32 +353,33 @@ NonsenseString: Line | 2 | NonsenseString | ~~~~~~~~~~~~~~ - | 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 try again. + | The term 'NonsenseString' is not recognized as a name of a cmdlet, +function, script file, or executable program. +Check the spelling of the name, or if a path was included, verify that the +path is correct and try again. ``` -In this example, the "function2 was completed" command was not run. In both +In this example, the `function2 was completed` command wasn't run. In both examples, the terminating error occurs within the function. In this example, -however, the `trap` statement is outside the function. PowerShell does not go +however, the `trap` statement is outside the function. PowerShell doesn't go back into the function after the `trap` statement runs. > [!CAUTION] > When multiple traps are defined for the same error condition, the first `trap` > defined lexically (highest in the script block) is used. -In the following example, only the `trap` with "whoops 1" is run. +In the following example, only the `trap` with `whoops 1` runs. ```powershell Remove-Item -ErrorAction Stop ThisFileDoesNotExist -trap { "whoops 1"; continue } -trap { "whoops 2"; continue } +trap { 'whoops 1'; continue } +trap { 'whoops 2'; continue } ``` > [!IMPORTANT] -> A Trap statement is scoped to where it compiles. If you have a -> `trap` statement inside a function or dot sourced script, when the function -> or dot sourced script exits, all `trap` statements inside are removed. +> A `trap` statement is scoped to where it compiles. If you have a `trap` +> statement inside a function or dot sourced script, when the function or dot +> sourced script exits, all `trap` statements inside are removed. ### Using the break and continue keywords @@ -368,11 +394,11 @@ in a `trap` statement: ```powershell function break_example { trap { - "Error trapped" + 'Error trapped' break } 1/$null - "Function completed." + 'Function completed.' } break_example @@ -387,12 +413,12 @@ Line | | Attempted to divide by zero. ``` -Because the `trap` statement included the `break` keyword, the function does -not continue to run, and the "Function completed" line is not run. +Because the `trap` statement included the `break` keyword, the function doesn't +continue to run, and the `Function completed` line isn't run. If you include a `continue` keyword in a `trap` statement, PowerShell resumes after the statement that caused the error, just as it would without `break` or -`continue`. With the `continue` keyword, however, PowerShell does not write an +`continue`. With the `continue` keyword, however, PowerShell doesn't write an error to the error stream. The following sample function uses the `continue` keyword in a `trap` @@ -401,11 +427,11 @@ statement: ```powershell function continue_example { trap { - "Error trapped" + 'Error trapped' continue } 1/$null - "Function completed." + 'Function completed.' } continue_example @@ -416,7 +442,7 @@ Error trapped Function completed. ``` -The function resumes after the error is trapped, and the "Function completed" +The function resumes after the error is trapped, and the `Function completed` statement runs. No error is written to the error stream. ## Notes diff --git a/reference/7.4/Microsoft.PowerShell.Core/About/about_Trap.md b/reference/7.4/Microsoft.PowerShell.Core/About/about_Trap.md index 3d3a2765dd4b..3f0af34b3433 100644 --- a/reference/7.4/Microsoft.PowerShell.Core/About/about_Trap.md +++ b/reference/7.4/Microsoft.PowerShell.Core/About/about_Trap.md @@ -1,7 +1,7 @@ --- description: Describes a keyword that handles a terminating error. Locale: en-US -ms.date: 05/26/2022 +ms.date: 01/17/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_trap?view=powershell-7.4&WT.mc_id=ps-gethelp schema: 2.0.0 title: about Trap @@ -14,7 +14,7 @@ Describes a keyword that handles a terminating error. ## Long description -A terminating error stops a statement from running. If PowerShell does not +A terminating error stops a statement from running. If PowerShell doesn't handle a terminating error in some way, PowerShell also stops running the function or script in the current pipeline. In other languages, such as C#, terminating errors are known as exceptions. @@ -24,8 +24,8 @@ error occurs. `trap` statements can handle the terminating errors in the following ways: - Display the error after processing the `trap` statement block and continuing - execution of the script or function containing the `trap`. This is the - default behavior. + execution of the script or function containing the `trap`. This behavior is + the default. > [!NOTE] > When the terminating error occurs in a subordinate script block, such as @@ -61,15 +61,15 @@ appear anywhere in the script or command. ### Trapping all terminating errors -When a terminating error occurs that is not handled in another way in a script +When a terminating error occurs that isn't handled in another way in a script or command, PowerShell checks for a `trap` statement that handles the error. If a `trap` statement is present, PowerShell continues running the script or command in the `trap` statement. -The following example is a very simple `trap` statement: +The following example is a minimal `trap` statement: ```powershell -trap {"Error found."} +trap { 'Error found.' } ``` This `trap` statement traps any terminating error. @@ -79,14 +79,14 @@ a runtime error. ```powershell function TrapTest { - trap {"Error found."} + trap { 'Error found.' } nonsenseString } TrapTest ``` -Running this function returns the following: +Running this function returns the following output: ```Output Error found. @@ -94,9 +94,10 @@ nonsenseString: Line | 3 | nonsenseString | ~~~~~~~~~~~~~~ - | 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 try again. + | The term 'nonsenseString' is not recognized as a name of a cmdlet, +function, script file, or executable program. +Check the spelling of the name, or if a path was included, verify that the +path is correct and try again. ``` The following example includes a `trap` statement that displays the error by @@ -104,26 +105,28 @@ using the `$_` automatic variable: ```powershell function TrapTest { - trap {"Error found: $_"} + trap { "Error found: $_" } nonsenseString } TrapTest ``` -Running this version of the function returns the following: +Running this version of the function returns the following output: ```Output 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 try again. +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 +try again. nonsenseString: Line | 3 | nonsenseString | ~~~~~~~~~~~~~~ - | 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 try again. + | The term 'nonsenseString' is not recognized as a name of a cmdlet, +function, script file, or executable program. +Check the spelling of the name, or if a path was included, verify that the +path is correct and try again. ``` > [!IMPORTANT] @@ -133,7 +136,7 @@ if a path was included, verify that the path is correct and try again. > In JavaScript, this is known as > [hoisting](https://wikipedia.org/wiki/JavaScript_syntax#hoisting). This means > that `trap` statements apply to all statements in that block even if -> execution has not advanced past the point at which they are defined. For +> execution hasn't advanced past the point at which they're defined. For > example, defining a `trap` at the end of a script and throwing an error in > the first statement still triggers that `trap`. @@ -146,12 +149,13 @@ The following example is a `trap` statement that traps the specific error **CommandNotFoundException**: ```powershell -trap [System.Management.Automation.CommandNotFoundException] - {"Command error trapped"} +trap [System.Management.Automation.CommandNotFoundException] { + 'Command error trapped' +} ``` -When a function or script encounters a string that does not match a known -command, this `trap` statement displays the "Command error trapped" string. +When a function or script encounters a string that doesn't match a known +command, this `trap` statement displays the `Command error trapped` string. After running the `trap` statement list, PowerShell writes the error object to the error stream and then continues the script. @@ -159,26 +163,44 @@ PowerShell uses .NET exception types. The following example specifies the **System.Exception** error type: ```powershell -trap [System.Exception] {"An error trapped"} +trap [System.Exception] { 'An error trapped' } ``` The **CommandNotFoundException** error type inherits from the -**System.Exception** type. This statement traps an error that is created by an -unknown command. It also traps other error types. +**System.Exception** type. This statement traps any errors raised by unknown +commands. It also traps other error types. + +You can find the exception type for an error by inspecting the error object. +The following example shows how to get the full name of the exception for the +last error in a session: + +```powershell +nonsenseString +$Error[0].Exception.GetType().FullName +``` + +```Output +nonsenseString: The term 'nonsenseString' is not recognized as a name of a +cmdlet, function, script file, or executable program. Check the spelling +of the name, or if a path was included, verify that the path is correct +and try again. + +System.Management.Automation.CommandNotFoundException +``` -You can have more than one `trap` statement in a script. Each error type can be -trapped by only one `trap` statement. When a terminating error occurs, -PowerShell searches for the `trap` with the most specific match, starting in -the current script block of execution. +You can have more than one `trap` statement in a script. Only one `trap` +statement can trap each error type. When a terminating error occurs, PowerShell +searches for the `trap` with the most specific match, starting in the current +script block of execution. The following script example contains an error. The script includes a general `trap` statement that traps any terminating error and a specific `trap` statement that specifies the **CommandNotFoundException** type. ```powershell -trap {"Other terminating error trapped" } +trap { 'Other terminating error trapped' } trap [System.Management.Automation.CommandNotFoundException] { - "Command error trapped" + 'Command error trapped' } nonsenseString ``` @@ -189,24 +211,26 @@ Running this script produces the following result: Command error trapped nonsenseString: Line | - 5 | nonsenseString - | ~~~~~~~~~~~~~~ - | 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 try again. + 5 | nonsenseString + | ~~~~~~~~~~~~~~ + | The term 'nonsenseString' is not recognized as a name of a cmdlet, +function, script file, or executable program. +Check the spelling of the name, or if a path was included, verify that the +path is correct and try again. ``` -Because PowerShell does not recognize "nonsenseString" as a cmdlet or other -item, it returns a **CommandNotFoundException** error. This terminating error -is trapped by the specific `trap` statement. +Because PowerShell doesn't recognize `nonsenseString` as a cmdlet or other +item, it returns a **CommandNotFoundException** error. The specific `trap` +statement traps this terminating error. The following script example contains the same `trap` statements with a different error: ```powershell -trap {"Other terminating error trapped" } -trap [System.Management.Automation.CommandNotFoundException] - {"Command error trapped"} +trap { 'Other terminating error trapped' } +trap [System.Management.Automation.CommandNotFoundException] { + 'Command error trapped' +} 1/$null ``` @@ -216,14 +240,14 @@ Running this script produces the following result: Other terminating error trapped RuntimeException: Line | - 4 | 1/$null + 5 | 1/$null | ~~~~~~~ | Attempted to divide by zero. ``` -The attempt to divide by zero does not create a **CommandNotFoundException** -error. Instead, that error is trapped by the other `trap` statement, which traps -any terminating error. +The attempt to divide by zero doesn't create a **CommandNotFoundException** +error. The other `trap` statement, which traps any terminating error, traps the +divide by zero error. ### Trapping errors in a script block @@ -231,9 +255,9 @@ By default, when a terminating error is thrown, execution transfers to the trap statement. After the `trap` block is run, control returns to the next statement block after the location of the error. -For example, when a terminating error occurs in an `foreach` statement, the `trap` -statement is run and execution continues at the next statement after the `foreach` block, -not within the `foreach` block. +For example, when a terminating error occurs in an `foreach` statement, the +`trap` statement is run and execution continues at the next statement after the +`foreach` block, not within the `foreach` block. ```powershell trap { 'An error occurred!'} @@ -252,19 +276,18 @@ after division 1 after division An error occurred! -RuntimeException: untitled:Untitled-1:3:4 +RuntimeException: Line | 3 | 1/$x | ~~~~ | Attempted to divide by zero. - after loop ``` -In the output above, you can see the loops continue until the last iteration. -When the script tries to divide 1 by 0 a terminating error is thrown. The rest -of the `foreach` scriptblock is skipped, the `try` statement is run, and the -script continues after the `foreach` scriptblock. +In the output, you can see the loops continue until the last iteration. When +the script tries to divide 1 by 0, PowerShell throws a terminating error. The +script skips the rest of the `foreach` script block, runs the `try` statement, +and continues after the `foreach` script block. ### Trapping errors and scope @@ -272,7 +295,7 @@ If a terminating error occurs in the same script block as the `trap` statement, PowerShell runs the list of statements defined by the `trap`. Execution continues at the statement after the error. If the `trap` statement is in a different script block from the error, execution continues at the next -statement that is in the same script block as the `trap` statement. +statement that's in the same script block as the `trap` statement. For example, if an error occurs in a function, and the `trap` statement is in the function, the script continues at the next statement. The following script @@ -280,9 +303,9 @@ contains an error and a `trap` statement: ```powershell function function1 { - trap { "An error: " } + trap { 'An error: ' } NonsenseString - "function1 was completed" + 'function1 was completed' } function1 @@ -296,26 +319,28 @@ NonsenseString: Line | 3 | NonsenseString | ~~~~~~~~~~~~~~ - | 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 try again. + | The term 'NonsenseString' is not recognized as a name of a cmdlet, +function, script file, or executable program. +Check the spelling of the name, or if a path was included, verify that the +path is correct and try again. function1 was completed ``` The `trap` statement in the function traps the error. After displaying the -message, PowerShell resumes running the function. Note that `Function1` was -completed. +message, PowerShell resumes running the function. Notice that `Function1` +completed after the `trap` statement. -Compare this with the following example, which has the same error and `trap` -statement. In this example, the `trap` statement occurs outside the function: +Compare this behavior with the following example, which has the same error and +`trap` statement. In this example, the `trap` statement occurs outside the +function: ```powershell function function2 { NonsenseString - "function2 was completed" + 'function2 was completed' } -trap { "An error: " } +trap { 'An error:' } function2 ``` @@ -328,32 +353,33 @@ NonsenseString: Line | 2 | NonsenseString | ~~~~~~~~~~~~~~ - | 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 try again. + | The term 'NonsenseString' is not recognized as a name of a cmdlet, +function, script file, or executable program. +Check the spelling of the name, or if a path was included, verify that the +path is correct and try again. ``` -In this example, the "function2 was completed" command was not run. In both +In this example, the `function2 was completed` command wasn't run. In both examples, the terminating error occurs within the function. In this example, -however, the `trap` statement is outside the function. PowerShell does not go +however, the `trap` statement is outside the function. PowerShell doesn't go back into the function after the `trap` statement runs. > [!CAUTION] > When multiple traps are defined for the same error condition, the first `trap` > defined lexically (highest in the script block) is used. -In the following example, only the `trap` with "whoops 1" is run. +In the following example, only the `trap` with `whoops 1` runs. ```powershell Remove-Item -ErrorAction Stop ThisFileDoesNotExist -trap { "whoops 1"; continue } -trap { "whoops 2"; continue } +trap { 'whoops 1'; continue } +trap { 'whoops 2'; continue } ``` > [!IMPORTANT] -> A Trap statement is scoped to where it compiles. If you have a -> `trap` statement inside a function or dot sourced script, when the function -> or dot sourced script exits, all `trap` statements inside are removed. +> A `trap` statement is scoped to where it compiles. If you have a `trap` +> statement inside a function or dot sourced script, when the function or dot +> sourced script exits, all `trap` statements inside are removed. ### Using the break and continue keywords @@ -368,11 +394,11 @@ in a `trap` statement: ```powershell function break_example { trap { - "Error trapped" + 'Error trapped' break } 1/$null - "Function completed." + 'Function completed.' } break_example @@ -387,12 +413,12 @@ Line | | Attempted to divide by zero. ``` -Because the `trap` statement included the `break` keyword, the function does -not continue to run, and the "Function completed" line is not run. +Because the `trap` statement included the `break` keyword, the function doesn't +continue to run, and the `Function completed` line isn't run. If you include a `continue` keyword in a `trap` statement, PowerShell resumes after the statement that caused the error, just as it would without `break` or -`continue`. With the `continue` keyword, however, PowerShell does not write an +`continue`. With the `continue` keyword, however, PowerShell doesn't write an error to the error stream. The following sample function uses the `continue` keyword in a `trap` @@ -401,11 +427,11 @@ statement: ```powershell function continue_example { trap { - "Error trapped" + 'Error trapped' continue } 1/$null - "Function completed." + 'Function completed.' } continue_example @@ -416,7 +442,7 @@ Error trapped Function completed. ``` -The function resumes after the error is trapped, and the "Function completed" +The function resumes after the error is trapped, and the `Function completed` statement runs. No error is written to the error stream. ## Notes