0

I use to log the function name which has exception . The code is as below

function sample {
    try{
        $functionname = "sample"
        throw "Error"
    }
    catch{
        write-error "[$functionName] :Exception occured "
        $_
    }
}

sample

Now the same thing i am trying to follow in class method. But the variable declared in try block is not visible in catch block.

class sample{

[string] samplemethod() {

    try{
        $MethodName = "SampleMethod"

        throw "error"

    }
    catch{
        Write-error "[$MethodName] : Exception occured"

        $_
    }
    return "err"
}

}

$obj = [sample]::new()
$obj.samplemethod()

It throws exception as below

At line:12 char:23 + Write-error "[$MethodName] : Exception occured" + ~~~~~~~~~~~ Variable is not assigned in the method.

Whether scope rule changed between class method and function?

Samselvaprabu
  • 16,830
  • 32
  • 144
  • 230
  • 2
    Parser simply more strict for classes. It not allow to read variable, if it is not guaranteed to be assigned in the method before use. Although it is easy to bypass. According to my knowledge, there are no scope rule changes here. – user4003407 Oct 11 '18 at 11:59

1 Answers1

-1

There is different scope exist in try catch blocks in addition to Class and methods.The variables declared in try block can not access from catch block. The below code should execute without any exception.
class sample{

[string] samplemethod() {
    $MethodName = "SampleMethod1"

    try{
        $test='hello'

        throw "error"

    }
    catch{
        Write-Host $MethodName
        Write-error "[$MethodName] : Exception occured"

        $_
    }
    return "err"
}

}

$obj = [sample]::new()
$obj.samplemethod()