Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to display a custom error message when a file is not found.
PowerShell
try { Get-Content -Path 'nonexistent.txt' } catch { Write-Host [1] }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the message
Using a variable name instead of a string
✗ Incorrect
The Write-Host command needs a string in quotes to display the custom error message.
2fill in blank
mediumComplete the code to throw a custom error with the message 'Invalid input detected'.
PowerShell
if ($input -eq $null) { [1] 'Invalid input detected' }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Write-Error instead of Throw for terminating errors
Using Write-Host which only prints text
✗ Incorrect
The Throw statement is used to generate a terminating error with a custom message.
3fill in blank
hardFix the error in the code to correctly catch and display a custom error message.
PowerShell
try { Remove-Item -Path 'C:\temp\file.txt' } catch { Write-Host [1] }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using $error which is a global array, not the current error
Using $_.Message which does not exist
✗ Incorrect
Inside catch, $_ represents the ErrorRecord object. $_.Exception.Message gives the error message.
4fill in blank
hardFill both blanks to create a function that throws a custom error with a given message.
PowerShell
function Throw-CustomError {
param([string]$msg)
[1] [2]
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Putting quotes around $msg which makes it a literal string '$msg'
Using Write-Error instead of Throw for terminating errors
✗ Incorrect
Throw is used to raise an error, and $msg passes the message string parameter.
5fill in blank
hardFill all three blanks to catch an error and throw a new custom error with a modified message.
PowerShell
try { Get-Item -Path 'C:\invalid\file.txt' } catch { $msg = $_.[1] $newMsg = "Custom error: $msg" [2] [3] }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using $_.Message instead of $_.Exception.Message for detailed error
Using Write-Error instead of Throw for terminating errors
Passing the variable name as a string instead of the variable value
✗ Incorrect
Use $_.Exception.Message to get the original error message, then Throw the new message stored in $newMsg.