# Exception Handling

## Throwing Exceptions

* The command **throw "Bad thing happened"** creates an exception and interrupts the script execution.
* The cmdlet **Write-Error -Message "Houston, we have a problem." -ErrorAction Stop** outputs an error, and setting **ErrorAction** to **Stop** causes the script to stop with this error.

## Exception Handling

The principle of error handling in PowerShell is based on the structure:

```powershell
try {
  # code where an error may occur
}
catch {
  # code to handle the error
}
finally {
  # code that always runs after try/catch
}
```

* The code in the `try` block runs first.
* If an unresolvable error occurs during the execution of `try`, control is passed to the `catch` block. If there are no errors, the `catch` block is skipped.
* In the `catch` block, the automatic variable `$PSItem` (or `$_`) of type `ErrorRecord` is available, which contains details of the exception.
* The `finally` block always executes, regardless of whether an error occurred or not. It is used to ensure that important code runs, such as closing connections or releasing resources.
* You can use both `catch` and `finally` at the same time. This allows you to handle errors while always performing cleanup actions, regardless of the outcome.

Example:

```powershell
try {
  throw "Bad thing happened"
}
catch {
  Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
}
finally {
  Write-Host "This block will always execute"
}
```

In this example, an exception is thrown via `throw`, then caught in `catch`, where an error message is displayed, and then the `finally` block executes, where cleanup code can be placed.

This model simplifies writing robust scripts with error management and resource cleanup.

This approach to exceptions helps create more resilient and maintainable PowerShell scripts, minimizing unexpected interruptions and ensuring timely responses to errors.

Additional information can be found at the link:

{% embed url="<https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-exceptions?view=powershell-7.1>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.sherparpa.ru/en/sherpa-rpa/sherpa-designer/sherpa-designer-otvety-na-chasto-zadavaemye-voprosy/powershell/obrabotka-isklyuchenii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
