1

I'm writing a PowerShell script with a try-catch that calls a bunch of functions.

function A {
  # exceptions here won't trigger the catch
}

function B {}

try {
  # exceptions here will trigger the catch

  A
  B
} catch {
  # handle errors
}

How do I get the functions to throw the exceptions upstream by default without writing a try catch block inside every functions?

3
  • It's not quite clear what you're expecting. Where these exceptions should be handled? Commented Mar 6, 2019 at 7:27
  • Take a look at (stackoverflow.com/questions/15545429/…) Commented Mar 6, 2019 at 8:14
  • Well, looks like it's working after all. I was having the problem where exceptions that happens inside a function doesn't trigger the catch block outside of it. But it's all good now. Commented Mar 7, 2019 at 0:32

2 Answers 2

1

As per my understanding, you are looking for capturing error of all the function without multiple try-catch. In this scenario, you can use an error logging mechanism to handle it:

function logger($val1 , $val2)
{
  try
  {
    echo $val1 $val2
    if ($val1 -eq 'Fail')
    { 
      "Wrong Input passed so it was logged as error" + $val1 | out-file -Filepath $logfile -append
    }
  }
  catch
  {
    $_.Exception.Message | out-file -Filepath $logfile -append
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Not really clear what exceptions your trying to throw but if you just manually want to throw and error to stop the script use the throw command.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.