1

I am trying to write something similar to this:

function Do-Something () {
  Write-Host "Starting something"
  Do-SomethingWhichThrowsAnException
  Write-Host "Something completed successfully"
}

...

function Process-Thing () {
  try {
    Do-OneThing
    Do-TwoThing
    Do-Something
    Do-SomethingElse
  }
  catch {
    Write-Host "Exception Caught!"
  }
}

And I get the following output:

Starting something
{massive red exception text}
Something completed successfully

Why do I not see "Exception Caught!"?

Why do I see "Something completed successfully"?

Does Powershell simply not throw exceptions up the stack or something?

If so, is it possible to slap it into submission? Do I have to try/catch inside every one of my Do-XXXthing functions?

Alex McMillan
  • 17,096
  • 12
  • 55
  • 88

1 Answers1

1

Check this article:

So, if I want to catch all errors that occur, I will catch a [System.Exception] because that is the root of all errors. Here is the Catch block I use:

Catch [System.Exception] {"Caught the exception"}

The next thing to realize is that if I try something, and it does not generate a terminating error, it will not move into the Catch block anyway. This is because the default for $ErrorActionPreference (what Windows PowerShell will do when an error arises) is to continue to the next command.

In reality, this means that if an error occurs and Windows PowerShell can recover from it, it will attempt to execute the next command. But it will let you know the error occurred by displaying the error to the console.

If I want to see what Windows PowerShell will do when a non-terminating error arises, I look at the value of the $ErrorActionPreference variable, for example:

PS C:> $ErrorActionPreference

Continue

...

So, I thing you should change the value of $ErrorActionPreferenceto Stop. Check the answer of this link about how to do this in a script.

Community
  • 1
  • 1
Moerwald
  • 10,448
  • 9
  • 43
  • 83