04 / MAKING DECISIONS · LESSON 16

Handle the unexpected

Catch a file error and always run cleanup.

12 min · learn at your pace

Errors are part of automation

A file can be missing. Data can be invalid. Good scripts make failures understandable instead of continuing with assumptions that are no longer true.

try, catch, and finally separate the work, failure handling, and cleanup:

try {
    Get-Content './missing.txt' -ErrorAction Stop
} catch {
    'The file could not be read.'
} finally {
    'Finished'
}

Make catch relevant

Many cmdlets write nonterminating errors by default. -ErrorAction Stop turns an error from that command into a terminating error that catch can handle. Without it, execution may continue without entering your catch block.

Inside catch, $_ contains the current error record. You can inspect $_.Exception.Message for more detail. In a reusable function, throw can report a failure to its caller.

finally runs after success or failure. It is useful for cleanup. Avoid turning every failure into a success message; provide an honest result that the next step can interpret.

Try an example.ps1
try {
    Get-Content './missing.txt' -ErrorAction Stop
} catch {
    $_.Exception.Message
}
YOUR TURN

Put it into practice.

Try to read ./missing-inventory.csv. Catch its error and output Inventory unavailable. In finally, output Finished.

See an explained solution
One way to solve it.ps1
try {
    Get-Content './missing-inventory.csv' -ErrorAction Stop
} catch {
    'Inventory unavailable'
} finally {
    'Finished'
}

The missing-file error transfers control into catch. Finally then runs, producing a predictable two-message result.