I’ve looked through the forums and hadn’t seen this particular question asked yet. My question is more best practice type on how often to use a try catch in a script? I’ve got fairly straight forward script to make to query a cluster about a whole bunch of things. I’m guilty of not doing enough error correcting in the past and picking up pieces after the fact, which I am trying to be better at in my future scripts. I’m getting bogged down in trying to handle all matter of possible exceptions and realized that I could have this kind of error checking on each command in the script. Is it better to have lean code, one that tries to address every potential issue or somewhere in the middle?
Like many things, it depends! Every line might be overkill.
What’s the worst that could happen? If these are queries, I’m assuming the worst is that you get bad data. Would that be a problem? If not, maybe you don’t need to worry about it.
If it’s not important, and you have other priorities, sure, go for leaner code.
But if it is important? Trust, buy verify : ) You might not need every line wrapped in try/catch, but do give thought to where you need it.
I can’t think of a single time I’ve seen code and wondered “why are they using so much error handling!” The other end of the spectrum I see all the time.
You may not need to put a Try / Catch everywhere.
Since you’re doing queries, you can wrap whole sections in a Try.
At various points in your code, set a variable like $SectionName = “Query mapped drives”
If you do encounter an error, in the Catch you can display/test the $SectionName variable.
It’ll will help narrow down the source of the error without excessive try/catch statements.