I am trying to catch a specific exception using PowerShell. Please see below example:
try {
throw [System.IO.FileNotFoundException]
}
catch [System.IO.FileNotFoundException] {
"File not found"
}
catch {
"Exception type: $($_.Exception.GetType().Name)"
}
Output from this code is: Exception type: RuntimeException
The output I am expecting is: "File not found"
What am I doing wrong here?
CodePudding user response:
You can't throw <typeName>
. You need to throw an instance of an exception type.
Change the throw
statement to:
throw [System.IO.FileNotFoundException]::new("Failed to find that file you asking for", "<attempted file name/path goes here>")