0
0
PowerShellscripting~10 mins

Try-Catch-Finally in PowerShell - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Try-Catch-Finally
Start Try Block
Run Code in Try
Error Occurs?
NoSkip Catch
|Yes
Run Catch Block
Run Finally Block
End
The script tries to run code in the Try block. If an error happens, it runs the Catch block. Finally, it always runs the Finally block.
Execution Sample
PowerShell
try {
  1 / 0
} catch {
  "Error caught"
} finally {
  "Always runs"
}
This script tries to divide 1 by 0, catches the error, and always runs the final block.
Execution Table
StepActionEvaluationOutput
1Enter Try blockExecute 1 / 0No output
2Error detectedJump to Catch blockNo output yet
3Execute Catch block"Error caught"Error caught
4Execute Finally block"Always runs"Always runs
5End scriptNo more codeScript ends
💡 Error in Try triggers Catch; Finally always runs; script ends after Finally
Variable Tracker
VariableStartAfter TryAfter CatchAfter Finally
OutputNoneError thrown"Error caught""Always runs"
Key Moments - 3 Insights
Why does the Catch block run even though the error happened inside Try?
Because the error in Try triggers the Catch block to handle it, as shown in execution_table step 2 and 3.
Does the Finally block run if there is no error?
Yes, Finally always runs after Try or Catch, shown in step 4 of the execution_table.
What happens if there is no error in Try?
Catch block is skipped and Finally runs, but in this example an error occurs so Catch runs.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 3?
ANo output
B"Error caught"
C"Always runs"
DError message
💡 Hint
Check the 'Output' column at step 3 in the execution_table.
At which step does the script detect an error?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Action' and 'Evaluation' columns to find when error detection happens.
If the division 1 / 0 was changed to 1 / 1, what would happen to the Catch block?
AIt would be skipped
BIt would run as normal
CIt would run after Finally
DIt would cause another error
💡 Hint
Refer to the key_moments about what happens if no error occurs in Try.
Concept Snapshot
Try-Catch-Finally in PowerShell:
try { # code that might fail }
catch { # code if error happens }
finally { # code that always runs }

- Try runs first
- Catch runs only if error in Try
- Finally runs always, no matter what
Full Transcript
This PowerShell script uses Try-Catch-Finally to handle errors. It tries to run code inside Try. If an error happens, it jumps to Catch to handle it. Finally always runs after Try or Catch. In the example, dividing 1 by 0 causes an error, so Catch runs and prints 'Error caught'. Then Finally runs and prints 'Always runs'. This shows how error handling works step-by-step.