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?
Test-Functioncatches 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