151

How I can create and throw a new exception in PowerShell?

I want to do different things for a specific error.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
user369182
  • 1,995
  • 4
  • 16
  • 17
  • 2
    Are you looking to throw a custom exception? Does [this][1] help? [1]: http://stackoverflow.com/questions/11703180/powershell-creating-a-custom-exception – bala_88 Aug 16 '12 at 05:46
  • 1
    Take a look at this post: http://stackoverflow.com/questions/2182666/powershell-2-0-try-catch-how-to-access-the-exception – Andrey Marchuk Aug 16 '12 at 07:58
  • You might be interested in https://adamtheautomator.com/powershell-logging/ – Dennis May 10 '23 at 15:21

2 Answers2

222

To call a specific exception such as FileNotFoundException use this format

if (-not (Test-Path $file)) 
{
    throw [System.IO.FileNotFoundException] "$file not found."
}

To throw a general exception use the throw command followed by a string.

throw "Error trying to do a task"

When used inside a catch, you can provide additional information about what triggered the error

WiiBopp
  • 2,750
  • 1
  • 14
  • 9
  • In C++, it is discouraged to throw strings, since they are not in the exception hierarchy. It just works, as in Powershell, but maybe they are not the best way to go? – Raúl Salinas-Monteagudo May 24 '19 at 11:35
  • 4
    If you are using try..catches in your script and you have multiple catch statements calling out specific exceptions then, of course, you would want to specify the exception type. I'm not certain why a reference is made to C++. In Powershell scripting, a throw statement is most usually intended to exit the script with a descriptive message. I'm not looking to spark a debate, but Powershell and C++ are extremely different animals. Applying C++ or C# best practices to Powershell should be tempered, since scripting is more closely associated with functional programming. – WiiBopp Jun 04 '19 at 16:15
10

You can throw your own custom errors by extending the Exception class.

class CustomException : Exception {
    [string] $additionalData

    CustomException($Message, $additionalData) : base($Message) {
        $this.additionalData = $additionalData
    }
}

try {
    throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
    # NOTE: To access your custom exception you must use $_.Exception
    Write-Output $_.Exception.additionalData

    # This will produce the error message: Didn't catch it the second time
    throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}
Dave F
  • 1,837
  • 15
  • 20