Powershell Try Catch in Higher Order Functions

I am trying to catch an Exception by calling a function that runs another function like this:

$ErrorActionPreference = "Stop"
function f {
    $a = 1
    $b = $a / 0
}
function Main($f) {
    try {
        $f
    } catch [System.Exception] {
        "Caught exception"
    }
}
Main(f)

The problem is that the Exception is not caught and PowerShell displays the message as follows:

Attempted to divide by zero.
In C:\test.ps1:4 car:5
+     $b = $a / 0
+     ~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : RuntimeException

Why is no exception detected even $ErrorActionPreference = "Stop"at the top of the code?

+4
source share
2 answers

Main(f). , , f Main. , , , Main. . PowerShell . , . Main ScriptBlock . ScriptBlock - , . . ScriptBlock. , , :

$ErrorActionPreference = "Stop"
function f {
    $a = 1
    $b = $a / 0
}

function Main {    
    param([ScriptBlock]$f)

    try {
        & $f
    } catch [System.Exception] {
        "Caught exception"
    }
}

Main -f { f }

, , f .

, C. , , PowerShell. PowerShell, .

ScriptBlock, - :

Main -f (get-command f).ScriptBlock
+3

, Main, f Main, Main. Set-PSDebug .

Set-PSDebug -Trace 2

:

Main(f)

DEBUG:     ! CALL function '<ScriptBlock>'
DEBUG:     ! SET $ErrorActionPreference = 'Stop'.
DEBUG:   15+  >>>> Main(f)
DEBUG:    2+ function f  >>>> {

DEBUG:     ! CALL function 'f'
DEBUG:    3+  >>>> 1/0

1.

function f {
1/1
}
function Main($f) {
    try {
        $f
    } catch [System.Exception] {
        "Caught exception"
    }
}

Main(f)

, :

function f {
1/1
}
function Main($f) {
    try {
        $f/0
    } catch [System.Exception] {
        "Caught exception"
    }
}

Main(f)

edit: , , :

function f {
$a = 0
1/$a
}
function Main($input) {
    try {
        $input
    } catch [System.Exception] {
        "Caught exception"
    }
}

Main(f)
+1

Source: https://habr.com/ru/post/1663929/


All Articles