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.
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.
#!/usr/bin/pwsh -Command#trying to divide by zero$result = 1/0$result
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.
#!/usr/bin/pwsh -Commandtry{$result = 1/0$result}catch{Write-Host "Divide by Zero is not allowed."}
In the above code:
try
block and provide our code which divides 1
by 0
in it.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.