Skip to content

Commit ec5c2a6

Browse files
authored
Add example for finally block (#11638)
* Add example for finally block * Fix code formatting
1 parent 5d58a94 commit ec5c2a6

File tree

3 files changed

+173
-96
lines changed

3 files changed

+173
-96
lines changed

reference/5.1/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md

Lines changed: 58 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,23 @@
11
---
22
description: Describes how to use the `try`, `catch`, and `finally` blocks to handle terminating errors.
33
Locale: en-US
4-
ms.date: 11/12/2021
4+
ms.date: 01/07/2025
55
online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_try_catch_finally?view=powershell-5.1&WT.mc_id=ps-gethelp
66
schema: 2.0.0
77
title: about_Try_Catch_Finally
88
---
99
# about_Try_Catch_Finally
1010

1111
## Short description
12+
1213
Describes how to use the `try`, `catch`, and `finally` blocks to handle
1314
terminating errors.
1415

1516
## Long description
1617

1718
Use `try`, `catch`, and `finally` blocks to respond to or handle terminating
1819
errors in scripts. The `Trap` statement can also be used to handle terminating
19-
errors in scripts. For more information, see [about_Trap](about_Trap.md).
20+
errors in scripts. For more information, see [about_Trap][05].
2021

2122
A terminating error stops a statement from running. If PowerShell does not
2223
handle a terminating error in some way, PowerShell also stops running the
@@ -71,9 +72,9 @@ Error types appear in brackets. The outermost brackets indicate the element is
7172
optional.
7273

7374
The `catch` keyword is followed by an optional list of error type
74-
specifications and a statement list. If a terminating error occurs in the
75-
`try` block, PowerShell searches for an appropriate `catch` block. If
76-
one is found, the statements in the `catch` block are executed.
75+
specifications and a statement list. If a terminating error occurs in the `try`
76+
block, PowerShell searches for an appropriate `catch` block. If one is found,
77+
the statements in the `catch` block are executed.
7778

7879
The `catch` block can specify one or more error types. An error type is a
7980
Microsoft .NET Framework exception or an exception that is derived from a .NET
@@ -117,7 +118,7 @@ block.
117118
PowerShell does not recognize "NonsenseString" as a cmdlet or other item.
118119
Running this script returns the following result:
119120

120-
```powershell
121+
```Output
121122
An error occurred.
122123
```
123124

@@ -132,16 +133,13 @@ two `catch` blocks:
132133

133134
```powershell
134135
try {
135-
$wc = new-object System.Net.WebClient
136-
$wc.DownloadFile("http://www.contoso.com/MyDoc.doc","c:\temp\MyDoc.doc")
137-
}
138-
catch [System.Net.WebException],[System.IO.IOException] {
136+
$wc = New-Object System.Net.WebClient
137+
$wc.DownloadFile("http://www.contoso.com/MyDoc.doc","c:\temp\MyDoc.doc")
138+
} catch [System.Net.WebException],[System.IO.IOException] {
139139
"Unable to download MyDoc.doc from http://www.contoso.com."
140-
}
141-
catch {
140+
} catch {
142141
"An error occurred that could not be resolved."
143142
}
144-
145143
```
146144

147145
The first `catch` block handles errors of the **System.Net.WebException** and
@@ -155,8 +153,9 @@ from the specified class. The following example contains a `catch` block that
155153
catches a "Command Not Found" error:
156154

157155
```powershell
158-
catch [System.Management.Automation.CommandNotFoundException]
159-
{"Inherited Exception" }
156+
catch [System.Management.Automation.CommandNotFoundException] {
157+
"Inherited Exception"
158+
}
160159
```
161160

162161
The specified error type, **CommandNotFoundException**, inherits from the
@@ -181,23 +180,23 @@ block for the derived class before the `catch` block for the general class.
181180
## Using Traps in a Try Catch
182181

183182
When a terminating error occurs in a `try` block with a `Trap` defined within
184-
the `try` block, even if there is a matching `catch` block, the `Trap` statement
185-
takes control.
183+
the `try` block, even if there is a matching `catch` block, the `Trap`
184+
statement takes control.
186185

187186
If a `Trap` exists at a higher block than the `try`, and there is no matching
188187
`catch` block within the current scope, the `Trap` will take control, even if
189188
any parent scope has a matching `catch` block.
190189

191190
## Accessing exception information
192191

193-
Within a `catch` block, the current error can be accessed using `$_`, which
194-
is also known as `$PSItem`. The object is of type **ErrorRecord**.
192+
Within a `catch` block, the current error can be accessed using `$_`, which is
193+
also known as `$PSItem`. The object is of type **ErrorRecord**.
195194

196195
```powershell
197196
try { NonsenseString }
198197
catch {
199-
Write-Host "An error occurred:"
200-
Write-Host $_
198+
Write-Host "An error occurred:"
199+
Write-Host $_
201200
}
202201
```
203202

@@ -210,21 +209,21 @@ script file, or operable program. Check the spelling of the name, or if a path
210209
was included, verify that the path is correct and try again.
211210
```
212211

213-
There are additional properties that can be accessed, such as **ScriptStackTrace**,
214-
**Exception**, and **ErrorDetails**. For example, if we change the script to the
215-
following:
212+
There are additional properties that can be accessed, such as
213+
**ScriptStackTrace**, **Exception**, and **ErrorDetails**. For example, if we
214+
change the script to the following:
216215

217216
```powershell
218217
try { NonsenseString }
219218
catch {
220-
Write-Host "An error occurred:"
221-
Write-Host $_.ScriptStackTrace
219+
Write-Host "An error occurred:"
220+
Write-Host $_.ScriptStackTrace
222221
}
223222
```
224223

225224
The result will be similar to:
226225

227-
```
226+
```Output
228227
An Error occurred:
229228
at <ScriptBlock>, <No file>: line 2
230229
```
@@ -240,10 +239,37 @@ A `finally` block runs even if you use <kbd>CTRL</kbd>+<kbd>C</kbd> to stop the
240239
script. A `finally` block also runs if an Exit keyword stops the script from
241240
within a `catch` block.
242241

242+
In the following example, the `try` block attempts to download a file to the
243+
`c:\temp` folder. The `catch` blocks handle errors that occur during the
244+
download. The `finally` block disposes of the `WebClient` object and removes
245+
the temporary file if it exists.
246+
247+
```powershell
248+
try {
249+
$wc = New-Object System.Net.WebClient
250+
$tempFile = "c:\temp\MyDoc.doc"
251+
$wc.DownloadFile("http://www.contoso.com/MyDoc.doc",$tempFile)
252+
} catch [System.Net.WebException],[System.IO.IOException] {
253+
"Unable to download MyDoc.doc from http://www.contoso.com."
254+
} catch {
255+
"An error occurred that could not be resolved."
256+
} finally {
257+
$wc.Dispose()
258+
if (Test-Path $tempPath) { Remove-item $tempFile }
259+
}
260+
```
261+
243262
## See also
244263

245-
- [about_Break](about_Break.md)
246-
- [about_Continue](about_Continue.md)
247-
- [about_Scopes](about_Scopes.md)
248-
- [about_Throw](about_Throw.md)
249-
- [about_Trap](about_Trap.md)
264+
- [about_Break][01]
265+
- [about_Continue][02]
266+
- [about_Scopes][03]
267+
- [about_Throw][04]
268+
- [about_Trap][05]
269+
270+
<!-- link references -->
271+
[01]: about_Break.md
272+
[02]: about_Continue.md
273+
[03]: about_Scopes.md
274+
[04]: about_Throw.md
275+
[05]: about_Trap.md

reference/7.4/Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md

Lines changed: 58 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,23 @@
11
---
22
description: Describes how to use the `try`, `catch`, and `finally` blocks to handle terminating errors.
33
Locale: en-US
4-
ms.date: 11/12/2021
4+
ms.date: 01/07/2025
55
online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_try_catch_finally?view=powershell-7.4&WT.mc_id=ps-gethelp
66
schema: 2.0.0
77
title: about_Try_Catch_Finally
88
---
99
# about_Try_Catch_Finally
1010

1111
## Short description
12+
1213
Describes how to use the `try`, `catch`, and `finally` blocks to handle
1314
terminating errors.
1415

1516
## Long description
1617

1718
Use `try`, `catch`, and `finally` blocks to respond to or handle terminating
1819
errors in scripts. The `Trap` statement can also be used to handle terminating
19-
errors in scripts. For more information, see [about_Trap](about_Trap.md).
20+
errors in scripts. For more information, see [about_Trap][05].
2021

2122
A terminating error stops a statement from running. If PowerShell does not
2223
handle a terminating error in some way, PowerShell also stops running the
@@ -71,9 +72,9 @@ Error types appear in brackets. The outermost brackets indicate the element is
7172
optional.
7273

7374
The `catch` keyword is followed by an optional list of error type
74-
specifications and a statement list. If a terminating error occurs in the
75-
`try` block, PowerShell searches for an appropriate `catch` block. If
76-
one is found, the statements in the `catch` block are executed.
75+
specifications and a statement list. If a terminating error occurs in the `try`
76+
block, PowerShell searches for an appropriate `catch` block. If one is found,
77+
the statements in the `catch` block are executed.
7778

7879
The `catch` block can specify one or more error types. An error type is a
7980
Microsoft .NET Framework exception or an exception that is derived from a .NET
@@ -117,7 +118,7 @@ block.
117118
PowerShell does not recognize "NonsenseString" as a cmdlet or other item.
118119
Running this script returns the following result:
119120

120-
```powershell
121+
```Output
121122
An error occurred.
122123
```
123124

@@ -132,16 +133,13 @@ two `catch` blocks:
132133

133134
```powershell
134135
try {
135-
$wc = new-object System.Net.WebClient
136-
$wc.DownloadFile("http://www.contoso.com/MyDoc.doc","c:\temp\MyDoc.doc")
137-
}
138-
catch [System.Net.WebException],[System.IO.IOException] {
136+
$wc = New-Object System.Net.WebClient
137+
$wc.DownloadFile("http://www.contoso.com/MyDoc.doc","c:\temp\MyDoc.doc")
138+
} catch [System.Net.WebException],[System.IO.IOException] {
139139
"Unable to download MyDoc.doc from http://www.contoso.com."
140-
}
141-
catch {
140+
} catch {
142141
"An error occurred that could not be resolved."
143142
}
144-
145143
```
146144

147145
The first `catch` block handles errors of the **System.Net.WebException** and
@@ -155,8 +153,9 @@ from the specified class. The following example contains a `catch` block that
155153
catches a "Command Not Found" error:
156154

157155
```powershell
158-
catch [System.Management.Automation.CommandNotFoundException]
159-
{"Inherited Exception" }
156+
catch [System.Management.Automation.CommandNotFoundException] {
157+
"Inherited Exception"
158+
}
160159
```
161160

162161
The specified error type, **CommandNotFoundException**, inherits from the
@@ -181,23 +180,23 @@ block for the derived class before the `catch` block for the general class.
181180
## Using Traps in a Try Catch
182181

183182
When a terminating error occurs in a `try` block with a `Trap` defined within
184-
the `try` block, even if there is a matching `catch` block, the `Trap` statement
185-
takes control.
183+
the `try` block, even if there is a matching `catch` block, the `Trap`
184+
statement takes control.
186185

187186
If a `Trap` exists at a higher block than the `try`, and there is no matching
188187
`catch` block within the current scope, the `Trap` will take control, even if
189188
any parent scope has a matching `catch` block.
190189

191190
## Accessing exception information
192191

193-
Within a `catch` block, the current error can be accessed using `$_`, which
194-
is also known as `$PSItem`. The object is of type **ErrorRecord**.
192+
Within a `catch` block, the current error can be accessed using `$_`, which is
193+
also known as `$PSItem`. The object is of type **ErrorRecord**.
195194

196195
```powershell
197196
try { NonsenseString }
198197
catch {
199-
Write-Host "An error occurred:"
200-
Write-Host $_
198+
Write-Host "An error occurred:"
199+
Write-Host $_
201200
}
202201
```
203202

@@ -210,21 +209,21 @@ script file, or operable program. Check the spelling of the name, or if a path
210209
was included, verify that the path is correct and try again.
211210
```
212211

213-
There are additional properties that can be accessed, such as **ScriptStackTrace**,
214-
**Exception**, and **ErrorDetails**. For example, if we change the script to the
215-
following:
212+
There are additional properties that can be accessed, such as
213+
**ScriptStackTrace**, **Exception**, and **ErrorDetails**. For example, if we
214+
change the script to the following:
216215

217216
```powershell
218217
try { NonsenseString }
219218
catch {
220-
Write-Host "An error occurred:"
221-
Write-Host $_.ScriptStackTrace
219+
Write-Host "An error occurred:"
220+
Write-Host $_.ScriptStackTrace
222221
}
223222
```
224223

225224
The result will be similar to:
226225

227-
```
226+
```Output
228227
An Error occurred:
229228
at <ScriptBlock>, <No file>: line 2
230229
```
@@ -240,10 +239,37 @@ A `finally` block runs even if you use <kbd>CTRL</kbd>+<kbd>C</kbd> to stop the
240239
script. A `finally` block also runs if an Exit keyword stops the script from
241240
within a `catch` block.
242241

242+
In the following example, the `try` block attempts to download a file to the
243+
`c:\temp` folder. The `catch` blocks handle errors that occur during the
244+
download. The `finally` block disposes of the `WebClient` object and removes
245+
the temporary file if it exists.
246+
247+
```powershell
248+
try {
249+
$wc = New-Object System.Net.WebClient
250+
$tempFile = "c:\temp\MyDoc.doc"
251+
$wc.DownloadFile("http://www.contoso.com/MyDoc.doc",$tempFile)
252+
} catch [System.Net.WebException],[System.IO.IOException] {
253+
"Unable to download MyDoc.doc from http://www.contoso.com."
254+
} catch {
255+
"An error occurred that could not be resolved."
256+
} finally {
257+
$wc.Dispose()
258+
if (Test-Path $tempPath) { Remove-item $tempFile }
259+
}
260+
```
261+
243262
## See also
244263

245-
- [about_Break](about_Break.md)
246-
- [about_Continue](about_Continue.md)
247-
- [about_Scopes](about_Scopes.md)
248-
- [about_Throw](about_Throw.md)
249-
- [about_Trap](about_Trap.md)
264+
- [about_Break][01]
265+
- [about_Continue][02]
266+
- [about_Scopes][03]
267+
- [about_Throw][04]
268+
- [about_Trap][05]
269+
270+
<!-- link references -->
271+
[01]: about_Break.md
272+
[02]: about_Continue.md
273+
[03]: about_Scopes.md
274+
[04]: about_Throw.md
275+
[05]: about_Trap.md

0 commit comments

Comments
 (0)