Begin, End, Try, Finally

This topic contains 5 replies, has 2 voices, and was last updated by  Olaf Soyk 2 months, 3 weeks ago.

  • Author
    Posts
  • #94449

    David Jones
    Participant

    The below code does not work due to finally not being directly associated with try/catch

    Is there a way to have the finally work when allying for pipeline input?

    placing an empty Try/Catch inside of end works, but I'm not sure if it will fire as expected if process throws a terminating error, and I don't want to leave the session open when the function exits.

    Begin {
      Try {
        # code to connect to import remote session
      } 
      catch {
        # error handeling
      }
    }
    Process {
      # do cooll stuff
    }
    end 
    {
      finally
      { 
       # remove remote session
      }
    }
    
  • #94452

    Olaf Soyk
    Participant

    A correct begin, process, end, try , catch, finally structure should look like this I think.

        begin {
            try {
            } 
            catch {
                throw
            }
            finally {
                
            }
        }
        process {
            try {
                
            } 
            catch {
                throw
            }
            finally {
                
            }
        }
        end {
            try {
            } 
            catch {
                throw
            }
            finally {
    
            }
        }

    So each block has its own error handling.

  • #94596

    David Jones
    Participant

    But will the finally in end run if the catch in process throws?

    • #94600

      Olaf Soyk
      Participant

      Hmmm .... yes and no. The Finally blocks always run, regardless of whether the Try block encounters a terminating error. But they are not related. If you need for whatever reason a relation between the Try and Catch block of the Process part and the Finally block of the End part you will have to create it by yourself.

      You might reread the help for this concept:

      Get-Help about_try_catch_finally

      😉

  • #94705

    David Jones
    Participant

    Finally blocks only run when the throw is in a catch, and only if they are in the same scope
    looks like my best option is to try/catch to turn termination into non-terminating so end still runs.

  • #94711

    Olaf Soyk
    Participant

    Well, the documentation tells us something else:

    About Try Catch Finally

    The finally block ALWAYS run. If you don't believe me or the documentation you should do your own research. 😉

    But yes – the Finally block hast to follow directly the catch block. But if you change the termination into non-terminating the catch block will not run – never – only if a terminating error occurs anyway.

You must be logged in to reply to this topic.