0

Take the below example.

Function Test-Function {
    try {
        [int]$var.ToString()
    }catch{
        Write-Error "Error inside Function"     
    }
}


try {
    Test-Function
}catch{
    Write-Error "Error inside try/catch of script"
}

Test-Function itself is generating an error (on purpose in this case, to test this behaviour), therefore hitting it's own catch. However, the Function call itself within the script, is also wrapped in a Try Catch statement, but the script only ever displays the catch of the function. Is this behaviour by design?

3
  • In .Net C# I've seen this many times and it's ok. When Test-Function catches an exception, error message it's more specific and that's the reason for nesting try/catch blocks. I personally don't do that but I re-throw the exception inside Test-Function catch block with new more descriptive error message so I only have to call my Logger once in the parent at the bottom of call stack. Here there's no Logger object, just a Write-Error, so it's ok. However I still prefer my method, as it aborts all execution at first error. Whereas the code you posted allows inconsistent code to keep running Commented Nov 23, 2017 at 18:56
  • I'm not sure I follow. Why doesn't the try catch calling the function catch an error? Commented Nov 23, 2017 at 18:58
  • 1
    because the error was already caught Commented Nov 23, 2017 at 19:02

1 Answer 1

4

The answer is how try-catch works and what Write-Error does. From Doc.Microsoft we know that....

The Write-Error cmdlet declares a non-terminating error

And looking at About_Try_Catch_Finally we see that it...

Describes how to use the Try, Catch, and Finally blocks to handle terminating errors.

Emphasis mine in both quotes

Try catch is not going to capture the output from Write-Error and that is by design. If you want to pass a terminating error use throw

Function Test-Function {
    try {
        [int]$var1.ToString()
    }catch{
        throw "Error inside Function"     
    }
}
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.