Ensures that one or more statements are always executed after a Try statement finishes.
Finally Statement
Finally
{
Statements
}
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.
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 the finally command. For example:
try { ... } finally { ... } try { ... } catch e { ... } finally { ... }
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 }