Hi,
Recently I found that when nest try/catch into another try/catch then I cannot specify error message in the nested try catch. For example:
try {
1 + 1
try {
1 / 0
} catch {
throw 'Small error'
}
} catch {
throw 'Big error'
}
In the example I got error message “Big error”. This is obvious since I “throw“ in the nested catch block. But how to get “Small error”?
I may have variable $customErrorMsg and save error message in it and then test it in the main catch. If variable exists, then use it for throw message. If doesn’t exist, then show “Big error” message.
Is there some best practice for that?
Thank you.
Bor
Hi Bor,
Truthfully I am not sure, if you simply throw, without the custom message, it works fine.
From what I understand, if you are nesting Try/Catch blocks, each inner block needs to generate a more specific error, since you are specifying two errors that are essentially just strings, maybe that is why (not sure). If you use
try {
1 + 1
try {
1 / 0
} catch {
throw 'Small error'
}
} catch {
throw
}
Then the inner catch works. I presume because specifying an error is ‘More specific’ than a system generated one (again, I’m just guessing at this stage).
One workaround would be to use
try {
1 + 1
try {
1 / 0
} catch {
Write-Warning "Small error"
}
} catch {
Write-Warning "Big error"
}
This way works, I have tested it with a few extra nests, and made it fail at different points, and you can still have custom error messages, or even mix them with system generated ones by adding $_ into the string. However, what you don’t get is the line number where it failed.