Try catch block - Separate or one large block

This topic contains 1 reply, has 2 voices, and was last updated by  nohwnd 2 weeks, 1 day ago.

  • Author
    Posts
  • #85040

    GlacialSpike
    Participant

    Is there any advantage/benefit to using one large, all inclusive try block at the start of a function, over smaller try blocks? For example:

    Function fooBar {
        try {
        New-Item ...
    
        if ($x = $y) { 
            ...
            }
    
        while ($i = 1) { 
             ....
            }
        }
        catch { }
    }
    

    Or alternatively, only try when using a cmdlet that is likely to throw an exception? e.g. Invoke-Command, New-Item, Set-Content etc?

    Which method is better practice?

    Thanks

  • #85051

    nohwnd
    Participant

    The best practice is to let the exception be unless you can recover from them.

    If you decide to catch an exception that you cannot handle make sure you rethrow it. Unless you are in a global exception handler and convert the error to: Something went wrong, sorry! Call our helpdesk with reference number 12304928341.

    You can also catch an exception and rethrow to give it more meaning. In this case throw new exception with the original exception as inner exception.
    try { } catch [FormatException] { throw new FormatException("The string is not a valid email", $_) }

    You can also catch on bigger pieces of code and log to report progress on bigger pieces of tasks, while still being able to progress to next task even if some task fails.

    foreach ($task in $tasks) {
    try {
    # do task
    }
    catch {
    $err += $_
    }
    }

    In this case I would always recommend to put the # do task in a function, because otherwise you cannot test it properly.

You must be logged in to reply to this topic.