Finally

AutoHotkey

Finally [v1.1.14+]

Ensures that one or more statements (commands or expressions) are always executed after the execution of a try statement.

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 instructions 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 commands 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.

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

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

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

Related

Try, Catch, Throw, Blocks

Examples

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
}