user9924807
user9924807

Reputation: 787

Catch a specific exception using PowerShell

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?

Upvotes: 1

Views: 253

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174465

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>")

Upvotes: 3

Related Questions