Challenge - 5 Problems
PowerShell Try-Catch-Finally Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate2:00remaining
What is the output of this PowerShell try-catch-finally script?
Consider this script that tries to divide numbers and handles errors:
PowerShell
try {
$result = 10 / 0
Write-Output "Result: $result"
} catch {
Write-Output "Error caught: $_"
} finally {
Write-Output "Cleanup done"
}Attempts:
2 left
💡 Hint
Remember dividing by zero causes an exception caught by catch block.
✗ Incorrect
Dividing by zero throws a runtime error. The catch block captures it and prints the error message. The finally block always runs, printing 'Cleanup done'.
🧠 Conceptual
intermediate1:30remaining
Which statement about PowerShell try-catch-finally is true?
Choose the correct statement about how try-catch-finally works in PowerShell.
Attempts:
2 left
💡 Hint
Think about when catch and finally blocks execute.
✗ Incorrect
Catch runs only when an error happens in try. Finally always runs regardless of error.
🔧 Debug
advanced2:30remaining
Why does this PowerShell script not catch the error?
Look at this script and find why the catch block never runs:
PowerShell
try {
Write-Output "Start"
Get-Item 'C:\nonexistentfile.txt'
Write-Output "End"
} catch {
Write-Output "Caught error"
} finally {
Write-Output "Done"
}Attempts:
2 left
💡 Hint
Check the type of error Get-Item throws by default.
✗ Incorrect
Get-Item throws non-terminating errors by default, which do not trigger catch. To catch, use -ErrorAction Stop.
🚀 Application
advanced3:00remaining
What is the output of this script with nested try-catch-finally?
Analyze this nested try-catch-finally script and select the correct output:
PowerShell
try {
Write-Output "Outer try start"
try {
Write-Output "Inner try start"
throw "Inner error"
Write-Output "Inner try end"
} catch {
Write-Output "Inner catch: $_"
} finally {
Write-Output "Inner finally"
}
Write-Output "Outer try end"
} catch {
Write-Output "Outer catch: $_"
} finally {
Write-Output "Outer finally"
}Attempts:
2 left
💡 Hint
Remember that the inner catch handles the inner throw, so outer catch is not triggered.
✗ Incorrect
The inner throw is caught by the inner catch, so outer catch does not run. Both finally blocks run. Outer try continues after inner finally.
🧠 Conceptual
expert3:00remaining
What happens if a finally block itself throws an error in PowerShell?
Consider a try-catch-finally where the finally block throws an error. What is the behavior?
Attempts:
2 left
💡 Hint
Think about error precedence when finally throws an error.
✗ Incorrect
If finally throws an error, it overrides any previous error and must be handled separately. Catch does not catch errors from finally.