From Xojo Documentation
Contains code that will run after a method or function is finished, even if a RuntimeException has occurred.
End [ Try ]
Sometimes a method needs to do some cleanup work whether it is finishing normally or aborting early because of an exception. The optional Finally block at the end of a method or function runs after its exception handlers, if it has any. Code in this block will be executed even if an exception has occured, whether the exception was handled or not.
More commonly you will use Finally as part of a Try...Catch statement.
For example, you can write:
// some code here...
// some more code that will always execute (unless a Return statement is used, see below)
However, the code in the Finally block does not execute if you exit the method with a Return statement. See the following code:
If x = 0 Then
Return // -> the Finally block won't execute
Break // Debugger would stop here to check if it executes
Returning From a Finally Block
Here is an example:
If you call this Test method, it will return as if there had been no exception raised inside. Therefore, avoid Return statements at all costs. If you really want to drop any raised exceptions, it is suggested that you be more explicit of that intention by adding a Catch block.
Also note that because a Return statement will skip any following Finally blocks, code that requires cleanup should be nested in its own Try block, with any return statement outside that block. Finally blocks at the method level are better avoided.
This simple example shows a Finally block that executes even after an exception.
Raise New RuntimeException
// Executes even though the exception is not handled
This example shows how to wrap code requiring cleanup inside a Try block, before returning a value.
Const libc = "libc.dylib"
Const libc = "libc.so"
Const O_RDONLY = &o0000
Soft Declare Function open Lib libc (path As CString, oflag As Integer) As Integer
Soft Declare Function read Lib libc (fildes As Integer, ByRef buf As Int64, nbyte As Integer) As Integer
Soft Declare Function close Lib libc (filedes As Integer) As Integer
Var theSeed As Int64
Var fd As Integer = open("/dev/random", O_RDONLY)
If fd = -1 Then
// an error occurred.
Const sizeOfInt64 = 8
Var read_bytecount As Integer = read(fd, theSeed, sizeOfInt64)
Var close_result As Integer = close(fd)
fd = -1