1
votes

That may not be the best title for this request.

I'm aware that I can wrap Powershell code in a try...catch block. I am also aware that I can set the $ErrorActionPreference variable.

However, rather than wrap the entire script in a big Try...Catch block, I would like to have some default code that will run when an unhandled exception occurs.

For instance, let's say some unexpected error occurs that is not caught by a try...catch. I would like PowerShell, before exiting (assuming ErrorActionPreference is STOP) to run a particular block of code so that the unexpected error can be logged or reported on.

Is there a way to do that?

2

2 Answers

1
votes

The "nice" way is to handle it with a try..catch block. They are mainly used to target specific sections of code and provide targeted exception handling. If you need something acting more "globally" you are likely wanting to use a Trap statement:

function TrapTest {
    trap {"Error found."}
    ...code

    CauseErrorHere

    ....code
}

Traps apply to the entire scope (e.g. function, script, etc.) and run when an exception happens. This allows you to log errors and also allow for the continuation of execution after the exception happens if you want.

0
votes

The finally part of the try...catch...finally block is generally used for this purpose.

try {
    # do some stuff
}
catch {
    # do some stuff on exception
}
finally {
    # do some stuff regardless of whether we caught an exception
}

You can also have just try and finally without the catch.