PowerShell try catch

In this article, I’ll explain how to use PowerShell try catch blocks for exception handling. Like any other programming language try and catch block PowerShell have the same syntax.

 

PowerShell try catch

 

PowerShell try catch block syntax

Try {

#Your code goes here

}
Catch {

# Exception handling code goes here

}

The Try block contains the code that may throw an exception. If an exception is thrown, control is transferred to the Catch block, where you can handle the exception thrown by try block.

You can also specify the type of exception you want to catch by using the Catch keyword followed by the exception type in square brackets:

 

Try {

# Your code goes here

}

Catch [System.IO.IOException] {

# Exception handling code for IO exceptions goes here

}
Catch {
# Exception handling code for all other exception types goes here

}

The above example has the first Catch block that will only handle IO Exceptions, while the second Catch block will handle all other exceptions thrown by the try block.

PowerShell try catch finally

In Addition to the above, we can use the finally block to specify a block of code that will always be executed, regardless of whether an exception was thrown or caught. This can be useful for cleaning up resources, dispose objects, closing opened files or any other actions that should be performed regardless of whether an exception occurred.

Here is an example of finally block with PowerShell try catch block in a script-

Try {

# Your code goes here

}
Catch {

# Exception handling code goes here

}

Finally {

# Cleanup code goes here

}

 

The finally block will be executed after the Try block and any Catch blocks have been completed. If an exception was thrown, the finally block will be executed after the exception has been caught and handled. If no exception was thrown, the finally block will be executed after the Try block has been completed successfully so in both cases whether an exception is thrown or not a finally block must be executed every time.

PowerShell try catch exception

Inside the Catch block, you can access the exception object using the variable $_. You can use this $_ object to get information about the exception thrown by a try block

Try {

# Your code goes here

}

Catch {

Write-Host $_.Exception.Source + ";"+ $_.Exception.Message +";" + $_.Exception.StackTrace

}

 

Conclusion

This is how you can use PowerShell try catch block for exception handling in PowerShell.