Reputation: 3185
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?
Upvotes: 0
Views: 281
Reputation: 46730
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"
}
}
Upvotes: 4