How to Handle Errors with Try-Catch in PowerShell?

Writing try-catch blocks in PowerShell to handle errors or exceptions is always a good idea. It ensures that your PowerShell scripts can handle unexpected situations gracefully and continue running or provide useful error messages. In PowerShell, you can use the TryCatch, and Finally blocks for error handling.

In this PowerShell tutorial, I will show you how to use try-catch blocks to implement error handling in PowerShell.

Errors in PowerShell

First, let us understand what are the errors in PowerShell.

Terminating Errors are severe errors that stop the script from continuing. These can be caused by commands that fail critically. When a terminating error occurs, the script execution halts unless handled by a try-catch block.

Non-terminating errors allow the script to continue running. These errors are often related to issues like missing files or operations that return errors but do not stop the script. Non-terminating errors get logged into the $Error variable, which keeps a collection of error records for review.

Below are the common errors in PowerShell.

  • Syntax Errors: These occur when the script contains invalid code or commands. Syntax errors need to be corrected before the script can run successfully.
  • Runtime Errors: These occur during the script execution when certain operations fail. Common runtime errors include file not found, permission denied, or invalid data format errors.

In PowerShell, when an error occurs, an ErrorRecord object is created. This object contains detailed information about the error, including the Exception message and the Category of the error. This information is crucial for debugging and fixing issues.

Using the PowerShell try-catch block helps handle these errors effectively.

So, now let us see how to implement the try-catch blocks in PowerShell.

Check out PowerShell Throw Exception with Message

What are Try, Catch, and Finally in PowerShell?

  • Try: This block contains the code you want to monitor for errors.
  • Catch: This block contains the code that you want to execute if an error occurs in the Try block.
  • Finally: This block contains the code that you want to execute regardless of whether an error occurs or not.

Syntax of PowerShell Try-Catch Finally block

A Try-Catch block in PowerShell is composed of two main parts: the Try block and the Catch block. The Try block contains the code that might cause an error. If an error occurs, the control moves to the Catch block. Here is the syntax of the PowerShell try-catch block:

try {
    # Code that may throw an exception
}
catch {
    # Code to handle the error
}

Below is the syntax for PowerShell try catch and finally block.

try {
    # Code that may throw an exception
}
catch {
    # Code to handle the error
}
finally {
    # Code that runs regardless of an error occurring or not
}

Here is a small example of how to use try catch and finally in PowerShell.

Let’s start with a simple example where we try to divide a number by zero, which will throw an exception.

try {
    $result = 10 / 0
    Write-Output "Result: $result"
}
catch {
    Write-Output "An error occurred: $_"
}
finally {
    Write-Output "Execution completed."
}

In this example, the catch block will capture the division by zero error and print an error message. The finally block will run regardless of whether an error occurred or not.

I executed the above PowerShell script, and you can see the output in the screenshot below:

powershell try catch finally example

Multiple Catch Blocks In PowerShell

Now, I will show you how to handle multiple catch blocks in PowerShell and how to handle specific exceptions in PowerShell to try to catch blocks.

You can have multiple catch blocks to handle different types of exceptions. This allows you to provide more specific error handling.

try {
    $result = [int]::Parse("abc")
}
catch [System.FormatException] {
    Write-Output "Format exception: $_"
}
catch {
    Write-Output "An unexpected error occurred: $_"
}
finally {
    Write-Output "Execution completed."
}

In this example, if the string “abc” cannot be converted to an integer, a System.FormatException will be caught by the first catch block. Any other exceptions will be caught by the second catch block.

You can see the output in the screenshot below:

Multiple Catch Blocks In PowerShell

PowerShell try catch finally example

Let us see how to use the PowerShell try catch finally block.

The finally block is useful for cleaning up resources, such as closing files or database connections, regardless of whether an error occurred.

Here is an example.

try {
    $file = [System.IO.StreamWriter]::new("example.txt")
    $file.WriteLine("Hello, World!")
    $file.Close()
}
catch {
    Write-Output "An error occurred: $_"
}
finally {
    if ($file -ne $null) {
        $file.Dispose()
        Write-Output "File closed."
    }
    Write-Output "Execution completed."
}

In this example, the finally block ensures that the file is closed even if an error occurs during writing.

Nested Try Catch in PowerShell

Let us see how to use nested try catch in PowerShell.

You can nest try blocks within each other to handle errors at different levels of your script. Here is a complete script.

try {
    try {
        $result = 10 / 0
    }
    catch {
        Write-Output "Inner catch: Division by zero error."
    }

    $result = [int]::Parse("abc")
}
catch [System.FormatException] {
    Write-Output "Outer catch: Format exception."
}
finally {
    Write-Output "Execution completed."
}

Here, the inner catch block handles the division by zero error, and the outer catch block handles the format exception.

PowerShell try catch continue

Here, I will show how to use the PowerShell try catch continue.

n PowerShell, you can use the TryCatch, and Finally blocks to handle errors, and you can also ensure that your script continues execution after an error occurs. This is particularly useful when you have a loop or a series of commands, and you want to catch errors for each iteration or command but not stop the entire script.

Here is an example of how to handle errors and continue execution.

Let’s consider a scenario where you have a list of server names and want to check each server’s status. If an error occurs while checking a server, you want to log the error and continue checking the remaining servers.

Here is the complete script.

# List of server names
$servers = @("Server1", "Server2", "NonExistentServer", "Server3")

foreach ($server in $servers) {
    try {
        # Simulate checking server status
        if ($server -eq "NonExistentServer") {
            throw "Server not found"
        }
        Write-Output "Successfully checked $server"
    }
    catch {
        Write-Output "Error checking $server: $_"
    }
    finally {
        Write-Output "Finished checking $server"
    }
}

Write-Output "Script completed"

Here is how the above PowerShell script works.

  • Server List: We have a list of server names, including one that does not exist ("NonExistentServer").
  • Loop Through Servers: We use a foreach loop to iterate through each server in the list.
  • Try Block: Inside the try block, we simulate checking the server status. If the server name is "NonExistentServer", we throw an error to simulate a server not found scenario.
  • Catch Block: The catch block captures the error and logs it. The $_ automatic variable contains the error message.
  • Finally Block: The finally block runs after the try or catch block, regardless of whether an error occurred. It logs that the server check is finished.
  • Continue Execution: The loop continues to the next server even if an error occurs, ensuring that all servers are checked.

When you run the script, the output will look like this:

Successfully checked Server1
Finished checking Server1
Successfully checked Server2
Finished checking Server2
Error checking NonExistentServer: Server not found
Finished checking NonExistentServer
Successfully checked Server3
Finished checking Server3
Script completed

This approach ensures that each server is checked, errors are logged, and the script continues execution without stopping due to an error.

PowerShell try catch specific error

Now, let us see one example of how to use PowerShell to catch specific error.

You can specify the type of exception you want to catch by providing the exception type in square brackets after the catch keyword. This allows you to handle different exceptions in different ways.

Let’s consider a scenario where you are performing multiple operations that can throw different types of exceptions, and you want to handle each exception type differently.

try {
    # Attempt to convert a string to a number (will throw a FormatException)
    $number = [int]::Parse("abc")
}
catch [System.FormatException] {
    Write-Output "Caught a format exception: $_"
}
catch [System.Exception] {
    Write-Output "Caught a general exception: $_"
}
finally {
    Write-Output "Execution completed."
}

Here’s another example where we handle multiple specific exceptions separately in PowerShell:

try {
    # Simulate a file operation that might throw different exceptions
    $fileContent = Get-Content -Path "nonexistentfile.txt"
}
catch [System.IO.FileNotFoundException] {
    Write-Output "Caught a file not found exception: $_"
}
catch [System.UnauthorizedAccessException] {
    Write-Output "Caught an unauthorized access exception: $_"
}
catch {
    Write-Output "Caught an unexpected exception: $_"
}
finally {
    Write-Output "Execution completed."
}

Throw Exception in PowerShell

I will show you here how to throw exceptions in PowerShell.

In PowerShell, the throw keyword is used to create a terminating error, which can be caught by a catch block.

Here is the syntax.

throw "Error message"

You can also throw specific exceptions using the throw keyword followed by an exception object.

throw [System.Exception]::new("Error message")

Let’s start with a simple example: We throw a general exception in PowerShell if a condition is not met.

function Check-Number {
    param (
        [int]$number
    )

    if ($number -lt 0) {
        throw "The number cannot be negative."
    }

    Write-Output "The number is $number"
}

try {
    Check-Number -number -5
}
catch {
    Write-Output "Caught an exception: $_"
}
finally {
    Write-Output "Execution completed."
}

Here is another example.

You can throw specific exceptions to provide more detailed error information. Here’s an example using System.ArgumentException.

function Validate-Input {
    param (
        [string]$input
    )

    if ([string]::IsNullOrEmpty($input)) {
        throw [System.ArgumentException]::new("Input cannot be null or empty.")
    }

    Write-Output "Valid input: $input"
}

try {
    Validate-Input -input ""
}
catch [System.ArgumentException] {
    Write-Output "Caught an argument exception: $_"
}
catch {
    Write-Output "Caught an unexpected exception: $_"
}
finally {
    Write-Output "Execution completed."
}

When you run the above script, the output will be:

Caught an argument exception: Input cannot be null or empty.
Execution completed.

This output indicates that the System.ArgumentException was caught by the specific catch block, and the finally block executed afterward.

PowerShell try catch examples

Now, let us see a few PowerShell try-catch examples.

Example 1: Handling File Not Found Exception

The below PowerShell script tries to read a file that does not exist, catches a System.IO.FileNotFoundException, and handles any other unexpected exceptions.

try {
    # Attempt to read a file that does not exist
    $fileContent = Get-Content -Path "nonexistentfile.txt"
}
catch [System.IO.FileNotFoundException] {
    Write-Output "Caught a file not found exception: $_"
}
catch {
    Write-Output "Caught an unexpected exception: $_"
}
finally {
    Write-Output "Execution completed."
}

Example 2: Handling Format Exception

The below script tries to convert an invalid string to an integer, catches a System.FormatException, and handles any other unexpected exceptions.

try {
    # Attempt to convert an invalid string to an integer
    $number = [int]::Parse("abc")
}
catch [System.FormatException] {
    Write-Output "Caught a format exception: $_"
}
catch {
    Write-Output "Caught an unexpected exception: $_"
}
finally {
    Write-Output "Execution completed."
}

Example 3: Custom Exception in a Function

This PowerShell script defines a function Check-Number that throws an exception if the provided number is negative. The calling code catches the exception and handles it.

function Check-Number {
    param (
        [int]$number
    )

    if ($number -lt 0) {
        throw "The number cannot be negative."
    }

    Write-Output "The number is $number"
}

try {
    # Call the function with an invalid number
    Check-Number -number -5
}
catch {
    Write-Output "Caught an exception: $_"
}
finally {
    Write-Output "Execution completed."
}

You can see in the screenshot below the output after I executed it using VS code.

PowerShell try catch examples

I hope you know now how to use try catch in PowerShell. I have also explained examples of PowerShell try-catch blocks.

You may also like:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.