Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need both try/catch and -ErrorAction?

The following code tries to copy the file test in three different ways, using two functions with different error management techniques:

  1. to itself (it should fail because it is impossible)
  2. to an hidden file (it should fail because hidden files cannot be overwritten by default)
  3. to a non existing folder (it should fail because the folder does not exist)

One of the two functions manages the errors with try/catch and is able to detect the first two errors, the other uses -ErrorAction and is able to detect the third error.

Is there one technique to catch all the errors?

Or do I always need to use both techniques?

function TestTryCatch($N, $Source, $Dest) {
    Write-Output "$N TestTryCatch $Source $Dest"
    try {Copy-Item $Source $Dest}
    catch {Write-Output "Error: $($error[0].exception.message)"}
}

function TestErrorAction($N, $Source, $Dest) {
    Write-Output "$N TestErrorAction $Source $Dest"
    Copy-Item $Source $Dest -ErrorAction SilentlyContinue
    if(!$?) {Write-Output "Error: $($error[0].exception.message)"}
}

New-Item 'test' -ItemType File | Out-Null
(New-Item 'hidden' -ItemType File).Attributes = 'Hidden'

TestTryCatch 1 'test' 'test'
TestTryCatch 2 'test' 'hidden'
TestTryCatch 3 'test' 'nonexistingfolder\test'

TestErrorAction 1 'test' 'test'
TestErrorAction 2 'test' 'hidden'
TestErrorAction 3 'test' 'nonexistingfolder\test'

Remove-Item 'test'
Remove-Item 'hidden' -Force
like image 408
stenci Avatar asked Sep 12 '26 14:09

stenci


1 Answers

Your first version should work to catch all errors if you use -ErrorAction Stop like so:

function TestTryCatch($N, $Source, $Dest) {
    Write-Output "$N TestTryCatch $Source $Dest"
    try {Copy-Item $Source $Dest -ErrorAction Stop}
    catch {Write-Output "Error: $($error[0].exception.message)"}
}

The key here is that Powershell differentiates between terminating and non-terminating errors, and non-terminating errors don't get caught by try {}. Using -ErrorAction Stop forces non-terminating errors to stop execution, and thus they get caught.

like image 175
briantist Avatar answered Sep 15 '26 02:09

briantist