1

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?

0

1 Answer 1

3

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>")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.