Try Catch - Style

After discussion with a colleague, I am informed my ‘style’ is wrong when using try catch statements. Which example is correct?

[pre]

try {
Test-Path -Path $filepath -PathType Leaf -EA Stop
} catch {
Write-Error -Message “File does not exist: $filepath”
}

[/pre]

Example 2:

[pre]

try {
Test-Path -Path $filepath -PathType Leaf -EA Stop
}
catch {
Write-Error -Message “File does not exist: $filepath”
}

[/pre]

If you’re just referring to the bracing style (i.e. the “cuddled” catch statement), neither is incorrect overall. This is just one of those things, like vim vs emacs, that has no particular answer but people will argue about for some time.

However, if your company has a defined coding standard - or the majority of the code in your company follows one of those examples, standardization is pretty useful. This might be what your colleague means.

You can see some discussion on the main bracing styles in use on the PoshCode practice and style repository.

Personally: I used to prefer example 2, but have since been converted to preferring 1 (OTBS) - mostly because it’s harder to accidentally insert something between the two blocks.

I personally prefer and do coding like example 2 as its more readable than 1, But yes, its all according to your organisation’s standard or based on the majority of existing code as mentioned by James.

These arguments are there in all languages which are too flexible in styling and formatting.

Consistency is key. As long as you follow the same construct for all instances (e.g. if / else, Try / Catch), you will keep the ire of your fellow scripters at bay.

Over course then you have the bracket battle too. I’ve always preferred the latter to keep all my brackets lined up

try {

vs

try

{

I prefer to use OTBS with Stroustrup ‘else’, ‘catch’, etc on a new line, as you do in example 2.

The reason I prefer the second example, is because it is (in my opinion) easier to read added comments. For example:

Example 1:

# Check if from the Netherlands.
if ($Country -eq 'Netherlands') {
    Write-Output "Do stuff"
}
# Not from the Netherlands
else {
    Write-Output "Do other stuff"
}

Compared to Example 2:

# Check if from the Netherlands.
if ($Country -eq 'Netherlands') {
    Write-Output "Do stuff"
} else { # Not from the Netherlands
    Write-Output "Do other stuff"
}

But there is no right or wrong. As Wes says, consistency is key.

My vote is #2. One thing that I see is code wrapping looks a bit awkward with version 1.

try {
}catch {}

vs

try {}
catch {}

I also prefer #2.

In general, it also makes it easier to read if you have lots of nested blocks and need to use the arrows to collapse when you are troubleshooting.

Coding style is and will always be argumentative. It’s like the whole tab vs space on the show Silicon Valley.

Your team has to decide on coding standards, either those used by industry references or those decided internally.

I see so much code where I personally disagree with the style, bring approaches from other languages due to misunderstanding or habits, that does not make it wrong, just not they way someone else would do it.

3 core things, IMHO:

  • readability (if they can't follow your stuff, then they will just re-write it. How long are you code lines? Are you using a bunch of shorthand, alias craziness that no one can follow or even know? )
  • maintainability (Can anyone who follows you deal with it without undue stress and strain? When I see your code, can I be assured that it will be reusable?)
  • consistency (When I see your code, is the following a standard or are you doing your code the same way, all the time?)
Note:

Many will argue about / for one way or the other, but if they don’t manage / pay you, work with you or collaborate with you, then it’s just their opinion that you personally have to accept, reject or take the parts the make since to your own style and deliveries.

Last Note:

There are times when bracing, bracketing, parenthetical, quoting, etc., will only work if they are done a certain way depending on what you are doing and what the language restrictions /confines are.

Like many have replied already which ever style works for you is best, the key is consistency. With that said I use my own style because for me it works better than either example above. Below is how I write all of my code blocks

try
  {
    1/0
  }
catch [DivideByZeroException]
  {
    Write-Host "Divide by zero exception"
  }
catch [System.Net.WebException],[System.Exception]
  {
    Write-Host "Other exception"
  }
finally
  {
    Write-Host "cleaning up ..."
  }

I like to indent my braces on a new line, further indent the command an another new line, then close the brace in the same position as the opening brace on yet another line. I find it easier read in general and to troubleshoot when everything lines up. Just my 2 cents.