Bird
0
0

Identify the error in this PowerShell script:

medium📝 Debug Q14 of 15
PowerShell - Error Handling
Identify the error in this PowerShell script:
try {
  throw "Missing file"
} catch {
  Write-Output "Error: $error"
}
AThe try block should not contain throw.
BThe throw statement is missing parentheses.
CThe catch block uses $error instead of $_ to get the error message.
DWrite-Output cannot be used inside catch.
Step-by-Step Solution
Solution:
  1. Step 1: Review error variable usage in catch

    Inside catch, the automatic variable $_ holds the current error. $error is an array of all errors, not the current one.
  2. Step 2: Identify correct variable for error message

    Using $error will output the entire error list, not the specific message. $_ is correct to get the thrown error message.
  3. Final Answer:

    The catch block uses $error instead of $_ to get the error message. -> Option C
  4. Quick Check:

    Use $_ in catch for error message = A [OK]
Quick Trick: Use $_ in catch, not $error, for current error message [OK]
Common Mistakes:
  • Using $error instead of $_ in catch
  • Thinking throw needs parentheses
  • Believing throw can't be inside try

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes