What is try catch in PowerShell?

Overview

The try-catch block is used to handle the errors in the PowerShell script. Generally, the program will terminate if it faces an error, but we can continue running it using the try-catch block.

Syntax

try{
#code
}
catch{
#handle error
}

We write our code in the try block, and the execution goes to the catch block if it faces any error while executing the code.

Let's look at an example of how we get errors, and we'll handle that error using a try-catch block.

Code 1

#!/usr/bin/pwsh -Command
#trying to divide by zero
$result = 1/0
$result

Explanation

In the above code, line 4, we deliberately try to divide 1 by 0 to get errors.

We will handle that error with custom output using a try-catch block in the following code snippet.

Code 2

#!/usr/bin/pwsh -Command
try{
$result = 1/0
$result
}
catch{
Write-Host "Divide by Zero is not allowed."
}

Explanation

In the above code:

  • Line 3: We declare a try block and provide our code which divides 1 by 0 in it.
  • Line 7: We declare a catch block to catch the error. When the try block throws an error, we handle it in the catch block and display the custom message.

Free Resources