Finally [v1.1.14+]

Ensures that one or more statements are always executed after a Try statement finishes.

Finally Statement
Finally
{
    Statements
}

Remarks

Every use of Finally must belong to (be associated with) a Try (or Catch) statement above it. A Finally always belongs to the nearest unclaimed Try statement above it unless a block is used to change that behavior.

Try statements behave differently depending on whether Catch or Finally is present. For more information, see Try.

Goto, Break, Continue and Return cannot be used to exit a Finally block, as that would require suppressing any control flow statements within the Try block. For example, if Try uses return 42, the value 42 is returned after the Finally block executes. Attempts to jump out of a Finally block using one of these statements are detected as errors at load time where possible, or at run time otherwise.

Prior to [v1.1.19.02], a bug existed which prevented control flow statements within Try from working when Finally was present. Return was erroneously permitted within Finally, but was ignored if an exception had been thrown.

Finally statements are not executed if the script is directly terminated by any means, including the tray menu, ExitApp, or Exit (when the script is not persistent). However, if only the current thread (not the entire script) is exiting, Finally statements are executed.

The One True Brace (OTB) style may optionally be used with Finally. For example:

try {
    ...
} finally {
    ...
}

try {
    ...
} catch e {
    ...
} finally {
    ...
}

Try, Catch, Throw, Blocks

Examples

Demonstrates the behavior of Finally in detail.

try
{
    ToolTip, Working...
    Example1()
}
catch e
{
    ; For more detail about the object that e contains, see Catch.
    MsgBox, 16,, % "Exception thrown!`n`nwhat: " e.what "`nfile: " e.file
        . "`nline: " e.line "`nmessage: " e.message "`nextra: " e.extra
}
finally
{
    ToolTip ; hide the tooltip
}

MsgBox, Done!

; This function has a Finally block that acts as cleanup code
Example1()
{
    try
        Example2()
    finally
        MsgBox, This is always executed regardless of exceptions
}

; This function fails when the minutes are odd
Example2()
{
    if Mod(A_Min, 2)
        throw Exception("Test exception")
    MsgBox, Example2 did not fail
}