You are right. When you use the default try/catch(/finally) statements all exception will be trapped in the catch block.
try {
Do-Someting
} catch {
Write-Host "Caught the following error: $($_.Exception.Message)"
} finally {
Write-Host "Finally, we made it!"
}
When you specifically add an exception to catch, you can create specific actions for that exception:
try{
Do-Something
} catch [System.Management.Automation.ItemNotFoundException]{
# catching specific exceptions allows you to have
# custom actions for different types of errors
Write-Host "Caught an ItemNotFoundException: $($_.Exception.Message)" -ForegroundColor Red
} catch {
Write-Host "General exception: $($_.Exception.Message)"
}
Try/Catchis the best approach to handle errors in Powershell. What is the purpose of handling any other "unexpeced" error? Isn't better handling specifically any part of code that actually could generate errors?Get-DateorSet-Variablein aTry/Catchblock makes the script unnecessary long imo. Additionally, those are commands that I've never seen failing to execute so I focus on rather instable parts of my scripts and useTry/Catchthere. Every other error can be an unexpected one since I literally do not expect my scripts to crash there.Get-DateorSet-Variable? How can you usefully handle them?ErrorCollectorin every script I make. The error then gets logged and is also stored in a variable with every other error that occured so far. At the end of every script a mail gets sent to my helpdesk IF at least one error occured or a notification has been set. That's why I also want to log unexpected errors. I just want to get notified of any error that occurs.