Try catch block - Separate or one large block

Welcome Forums General PowerShell Q&A Try catch block - Separate or one large block

This topic contains 1 reply, has 2 voices, and was last updated by

1 year, 3 months ago.

  • Author
  • #85040

    Points: 13
    Rank: Member

    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?


  • #85051

    Points: -19
    Rank: Member

    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.

The topic ‘Try catch block - Separate or one large block’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort