Try-Catch-Finally helps you handle errors in your script so it doesn't stop unexpectedly. It lets you try code, catch errors, and always run cleanup code.
When you want to run a command but handle possible errors without stopping the script.
When you need to log or show a friendly message if something goes wrong.
When you want to make sure some code runs no matter what, like closing a file or releasing resources.
When you want to separate normal code from error handling code for clarity.
When debugging scripts to catch and understand errors.
Syntax
PowerShell
try {
# Code that might cause an error
} catch {
# Code to handle the error
} finally {
# Code that always runs
}
The try block contains code that might fail.
The catch block runs only if an error happens in try.
Examples
This tries to read a file. If the file is missing, it shows a message instead of stopping.
The script uses finaly instead of the correct finally keyword.
Step 2: Verify other syntax elements
Catch does not require parentheses, and semicolons are optional in PowerShell; so these are not errors.
Final Answer:
Misspelled 'finally' keyword -> Option C
Quick Check:
Keyword spelling matters: 'finally' correct = B [OK]
Hint: Check spelling of 'finally' carefully [OK]
Common Mistakes:
Thinking catch needs parentheses
Expecting semicolons after commands
Missing typo in finally keyword
5. You want to ensure a log file is always closed after writing, even if an error occurs during writing. Which Try-Catch-Finally structure correctly achieves this?
The correct order is try, then catch, then finally. The finally block always runs last.
Step 2: Identify correct usage for closing log file
try { Write-Output 'Write log' } catch { Write-Output 'Error' } finally { Close-LogFile } correctly places Close-LogFile in finally to ensure it runs always, even if an error occurs.