0
0
PowerShellscripting~5 mins

Try-Catch-Finally in PowerShell

Choose your learning style9 modes available
Introduction

Try-Catch-Finally helps you handle errors in your script so it doesn't stop unexpectedly. It lets you try code, catch errors, and always run cleanup code.

When you want to run a command but handle possible errors without stopping the script.
When you need to log or show a friendly message if something goes wrong.
When you want to make sure some code runs no matter what, like closing a file or releasing resources.
When you want to separate normal code from error handling code for clarity.
When debugging scripts to catch and understand errors.
Syntax
PowerShell
try {
    # Code that might cause an error
} catch {
    # Code to handle the error
} finally {
    # Code that always runs
}

The try block contains code that might fail.

The catch block runs only if an error happens in try.

Examples
This tries to read a file. If the file is missing, it shows a message instead of stopping.
PowerShell
try {
    Get-Content 'file.txt'
} catch {
    Write-Host 'File not found.'
}
This tries to divide by zero, catches the error, shows a message, and always prints 'Done trying division.'
PowerShell
try {
    1 / 0
} catch {
    Write-Host 'Cannot divide by zero.'
} finally {
    Write-Host 'Done trying division.'
}
Sample Program

This script tries to divide 10 by zero, which causes an error. The catch block shows a friendly message. The finally block runs always.

PowerShell
try {
    $number = 10
    $result = $number / 0
    Write-Host "Result is $result"
} catch {
    Write-Host "Oops! You can't divide by zero."
} finally {
    Write-Host "This runs no matter what."
}
OutputSuccess
Important Notes

Use finally to clean up resources like files or connections.

If no error happens, the catch block is skipped.

Errors caught by catch are called terminating errors in PowerShell.

Summary

Try-Catch-Finally helps manage errors smoothly in scripts.

try runs code that might fail, catch handles errors, and finally runs always.

This makes scripts more reliable and user-friendly.