Try Catch - Style

Welcome Forums General PowerShell Q&A Try Catch - Style

This topic contains 9 replies, has 10 voices, and was last updated by

 
Participant
1 month ago.

  • Author
    Posts
  • #120735

    Participant
    Points: 13
    Rank: Member

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

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

    Example 2:

    
    try {
    Test-Path -Path $filepath -PathType Leaf -EA Stop
    }
    catch {
    Write-Error -Message "File does not exist: $filepath"
    }
    
    
  • #120751

    Moderator
    Points: 102
    Team MemberHelping Hand
    Rank: Participant

    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.

  • #120759

    Participant
    Points: 870
    Helping Hand
    Rank: Major Contributor

    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.

  • #120772

    Moderator
    Points: 174
    Team MemberHelping Hand
    Rank: Participant

    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.

  • #120783

    Participant
    Points: 9
    Rank: Member

    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
    
    {
  • #120826

    Participant
    Points: 112
    Helping Hand
    Rank: Participant

    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.

  • #120834

    Participant
    Points: 316
    Helping Hand
    Rank: Contributor

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

    try {
    }catch {}
    

    vs

    try {}
    catch {}
    
  • #122918

    Participant
    Points: 62
    Team Member
    Rank: Member

    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.

  • #122919

    Participant
    Points: 319
    Helping Hand
    Rank: Contributor

    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.

  • #122961

    Participant
    Points: 110
    Helping Hand
    Rank: Participant

    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.

You must be logged in to reply to this topic.