Error and exception handling – Try/Catch
One of the more popular error and exception handling techniques is leveraging Try/Catch
methodology. The Try/Catch
block is used for handling terminating errors and has a very simple structure. You first use the Try { }
section of code and then use Catch { }
to catch any errors and perform actions based on the errors. In the instance that you catch an error, you can access the exception object by declaring $_
. The $_
refers to what is in the current pipeline. Since an error occurred during the Try
sequence, the data in the pipeline is the actual error information.
To use the Try/Catch
block, do the following action:
Try { 1+ "abcd" } Catch { Write-host "Error Processing the Command: $_" } Write-host "" Write-host "Attempting to Add a String without Exception Handling:" 1+ "abcd"
The output of this is shown in the following screenshot:
The preceding example shows how you have the ability to leverage the Try/Catch
block during runtime. In this example...