Try/Catch Question

I am a big fan of try/catch blocks. My question is guidelines and limits to nesting try/catch blocks. Is there a best practice on nesting and or good/bad ideas? I basically use the nesting as a fallback … here is some pseudo code:

try {
    Do-Something
}
catch {
       # Dang, that failed, lets try something else
       try {
           do-somethingelse
       }
       catch {
           Throw-Error
      }
}

I have some situations where I actually nest to a third level. My basic goal is to never have the script choke hard and not complete. Wondering if this is a bad idea and if there is a limit to the number of nested try/catch blocks in PowerShell. I did find this on ChatGPT.

In PowerShell, you can indeed nest try/catch/finally blocks, and there is no specific limit to how many levels of nesting you can have. Each try block can contain multiple catch blocks and a single finally block. Here’s a simplified example to demonstrate nested try/catch behavior

Thanks in advance for any and all opinions :slight_smile:

I think this is a great question, one I’ve thought about a couple times. There’s also the variant of doing it within the try block:

try {
     Get-Something
     try {
          Do-SomethingElse
     } catch {
          something
     }
} catch {stuff}

I am not sure I have the best way and I’m certainly open to others opinions. My personal strategy is to limit the nesting of try/catches but understand there may be exceptions/situations so try not to worry too much if others do it (unless it is excessive).

I’ve not had very many needs for a nested try catch. I’m sure I’ve done it though and I could probably go find older code and re-do it to maybe work around it.

I’m not a programmer by background but have heard that try/catches are ‘expensive’ and should be limited in general, so I’ve always done that to begin with. For the types of things I work on that’s usually not a big deal, but I still try to use too many of them, and I also try to avoid nesting them. I feel like it’s easier to follow code if nested try/catches are limited/not used. However, I do nest if/else statements sometimes, but even those I try to limit as I can usually re-work it to not do any crazy amount of nesting. I feel like it’s more readable and helps make debugging easier. I’ve generally been able to-refactor things, or in some situations, I’ve simply been able to use multiple catch statements or if/else logic within a catch if I needed some additional control over what happened. In some cases, maybe all I really care about is whether or not I got something returned, so I might just ignore error messages altogether and just check the value and do something if that value is null, which sort of works around the issue in some situations. It’s just situational to the task at hand.

However, I think it’s probably a topic of debate among many. There might be situations where an inner try catch is needed to do some additional thing that you also want a try catch for. I’d love to hear other thoughts and experiences.

I know this is just an example, but in this case, the inner try-catch could be eliminated by just having Do-SomethingElse throw the error (-Erroraction Stop or something).

But I have used a scenario like this:

try {
    Do-Something
}
catch {
       # Dang, that failed, lets try something else
       try {
           do-somethingelse
       }
       catch {
           # Nope, that didn't work either - last resort
           do-anotherthing
      }
}

I need Do-SomethingElse to do more than throw an error and if Do-SomethingElse fails, then I need to throw and log the error.

The main reason I posed this question is the number of threads on a google search that basically said Try/Catch blocks are a bad idea. I personally use them all the time and see them as a useful way to keep the script moving forward and not choking hard.

Thanks for your input :slight_smile:

I was assuming Do-SomethingElse was a command, function, or code block that would attempt to do something, and if it fails to do it, it would throw an error. Like Do-SomethingElse -ErrorAction Stop. That’s the only way the catch would run.

Or saying this another way, putting a throw in the catch block by itself is redundant. The original command threw an error for the catch to run - if Do-SomethingElse should throw an error if it fails, then it should throw an error without a try/catch.

And yes, I may have drifted from your original question completely. I recently ran into a case in code where it was doing the same thing as your example. I eliminated the second try/catch by letting the command’s error message be sufficient, instead of catching the command’s error and then throwing my own. Apologies if this went into the weeds :slight_smile:

So, your thoughts? In general, do you try to avoid them and think they are a bad idea? I am always trying to use best practices and would be interested in the thoughts of those on this forum.

I use them extensively. Too many times I’ve been burned by the dumbest cmdlets so I set $erroractionpreference = 'Stop' at the beginning of my script and a try catch around single commands up to groups of related commands/actions. I’ve seen plenty of long term powershellers wrap the entire script in a single try/catch as a safetynet to always be able to handle exiting gracefully.

And I do the same Doug. Thanks for your input. I was just surprised at how many google search results said they were a bad idea and poor coding.

I know, I’m late to the party. But you explicitly asked for my opinion. :man_shrugging:t3:

I actually only use try catch if I come across an error during the development or test of the script/module/function/snippet interfearing the result.
Sometimes a function is for my colleagues (we are a team of only 4) and I know they can handle it. Then I don’t even bother. :man_shrugging:t3:
If I actually write some code for users or “low level admins from clients” I mostly just try to make it as robust as necessary. It does not have to be bullet prove. If errors happen when I released the code I still can fix it. And our client is very understanding and forgiving.

Just my 2 ct. :blush: :love_you_gesture:t3: