PowerShell: How to Use Try / Catch / Finally


You can use try, catch and finally in PowerShell for error handling.

Here is what each of these do:

A try statement “tries” to perform some operation.

A catch block specifies some action to perform if there is an error in the try statement.

A finally block performs some action after the try and catch and will always run, regardless of whether or not there were any errors.

We can use the following basic syntax to use try, catch and finally together:

try
{
    1/0
}
catch
{
    Write-Host "There was an error."
}
finally
{
    Write-Host "The task is complete."
}

The following example shows how to use try, catch and finally in practice.

Example: How to Use Try / Catch / Finally in PowerShell

Suppose that we would like to attempt to divide 1 by 0.

Suppose we type this operation in PowerShell without using a try statement:

We receive a message that says we attempted to divide by zero along with additional details.

Suppose that we would like to perform this exact same operation but display our own custom output if an error occurs.

We could use the following syntax with try, catch and finally to do so:

try
{
    1/0
}
catch
{
    Write-Host "There was an error."
}
finally
{
    Write-Host "The task is complete."
}

The following screenshot shows how to use this syntax in practice:

PowerShell try catch finally example

Since it’s not possible to divide 1 by 0, the catch block displays the following message:

  • There was an error.

The finally block then produces the following message to indicate that the try and catch blocks have been run:

  • The task is complete.

Suppose instead that we try to multiply 1 by 0:

try
{
    1*0
}
catch
{
    Write-Host "There was an error."
}
finally
{
    Write-Host "The task is complete."
}

The following screenshot shows how to use this syntax in practice:

PowerShell try, catch, finally with no errors

Since it’s possible to multiply 1 by 0, the try statement produces the result of this multiplication, which is 0.

The catch block has no error to catch, so it doesn’t produce any output.

The finally block then produces the following message to indicate that the try and catch blocks have been run:

  • The task is complete.

Note that in both examples the message from the finally block is shown in the output, regardless of whether or not any error occurred.

In practice, you aren’t required to use a finally block with try and catch blocks, but it can be useful to place at the end of a script to indicate that all operations attempted in the script have been completed.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to List Files in Directory by Date
PowerShell: How to List All Files in Directory to Text File
PowerShell: How to Delete All Files with Specific Extension

Leave a Reply